jeev
jeev

Reputation: 183

Android correct place to intialize LocalBroadcastReceiver for an activity

I have an android activity that has BroadcastReceiver as below.

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, intentFilter);
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          Log.i("TAG", intent.getAction());
        }
};

The problem is I am receiving message from network and depending on message type I create the activity or send Broadcast message to activity, since I receive message very fast the message type to create activity arrives right before(in few milliseconds) the message type to send Broadcast message to the same activity and I get an error handleWindowVisibility: no activity for token android.os.BinderProxy researching a bit I found that the activity might not be created correctly before I send the broadcast intent. So I made the thread sleep for 3 seconds.

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

Now everything works as expected but the above looks ugly and a bit hackish, is there a better way to send broadcast intent right before the activity creation?

Upvotes: 1

Views: 62

Answers (1)

David Wasser
David Wasser

Reputation: 95578

Instead of creating the Activity and sending a broadcast Intent to it, just put the contents of the broadcast Intent in the Intent you use to start the Activity (as an "extra"). Then you don't need the 3 second delay, you just only send the broadcast Intent if the Activity is already running.

Upvotes: 0

Related Questions