1

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?

ashley
  • 181
  • 1
  • 8
  • Could you post the [stack trace](/a/23353174) of the exception? – Ryan M Apr 26 '20 at 23:50
  • I see the error that get logged in logcat without any exception or app crash, so i don't have any stacktrace – ashley Apr 26 '20 at 23:57
  • Hmm, it's hard to tell without seeing the rest of the code, but I suspect that the problem is what you're doing once you receive the message (that is, you're doing something that relies on something that's not available). – Ryan M Apr 27 '20 at 02:35
  • You are probably filtering your logcat which is why you don't see the stacktrace. Try to disable filtering and see if you see the full exception log. – David Wasser May 09 '20 at 13:38

1 Answers1

0

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.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • There are multiple paths to start the activity and some path might not have the Intent already present so removing broadcast Intent is not possible. – ashley May 09 '20 at 12:27
  • Then you'll need to find the whole stack trace in the logcat and post that so we can see where the code is crashing. I don't have enough info to help you any more than this. – David Wasser May 09 '20 at 13:40