S
S
Sergey Semenko2017-02-14 23:07:50
Android
Sergey Semenko, 2017-02-14 23:07:50

Android. Is it allowed to do so?

I need to make an event system, I decided to use LocalBroadcastManager:

public abstract class BaseFragment extends Fragment
{
    private static final String USER_LOGIN_ACTION = "user_login_action";

    private LocalBroadcastManager localBroadcastManager;

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case USER_LOGIN_ACTION:
                    User user = Parcels.unwrap(intent.getParcelableExtra("user"));
                    onUserLogin(user);
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(USER_LOGIN_ACTION);

        localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }

    public void fireUserLogin(User user) {
        Intent intent = new Intent(USER_LOGIN_ACTION);
        intent.putExtra("user", Parcels.wrap(user));
        localBroadcastManager.sendBroadcast(intent);
    }

    public void onUserLogin(User user) {
        //
    }
}

How do you feel about this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
z0rgoyok, 2017-02-15
@z0rgoyok

Try EventBus it's cooler

R
Rou1997, 2017-02-15
@Rou1997

I feel the same way about this as I do about this example of recursion:

void tryConnectToServer() {
 tryConnectToServer();
}

Where is the point?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question