1

I have a BroadcastReceiver() and the onReceive method is called even when the app is suspended/dead. I want the onReceive only to be called when the user opens the notification from the home screen, how can I do that?

MainClass:

 broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            }
    };

    final Intent intent = registerReceiver(broadcastReceiver, intentFilter);

BroadCastReceiver class

 Intent intent;
    if(rootActivity.getPackageName().equalsIgnoreCase("myapp"))
    {
        //your app is open
        intent = new Intent();
        intent.setComponent(rootActivity);

    } else {
        //your app is not open,start it by calling launcher activity
        intent = new Intent(context, MainActivity.class);
    }

    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(contentIntent);

Manifest

 android:launchMode="singleTop"
cal
  • 470
  • 1
  • 7
  • 27
  • 1
    Just unregister your receiver when your activity is destroyed. – Alex Kamenkov Oct 02 '16 at 11:30
  • Then I do not really understand the question, if you want to be notified only when activity is running then register your receiver when activity starts and unregister it when activity is destroyed. – Alex Kamenkov Oct 02 '16 at 11:48
  • If I unregister the receiver then no notifications are received when the app is in "forced stop" state. Is it possible to receive notifications in this situation? I see that the Twitter app does for example... – cal Oct 02 '16 at 11:54
  • Actually no notifications after force stop seems intended behaviour for android, so unregister works! – cal Oct 02 '16 at 12:01

0 Answers0