startActivity not working when calling from BroadcastReceiver

user1163234 picture user1163234 · Feb 11, 2015 · Viewed 7k times · Source

I have a notification and when I select, it sends a Broadcast to a BroadcastReceiver using a PendingIntent. In the onReceive I start a new Activity.

However, if I remove my app from recent apps opened (or the notification sit in the draw for a long time) this scenario occurs:

When I have multiple notifications in the drawer the first one opens great. After tapping on the second one my onCreate() nor my onResume() are being called and its as if the startActivity() is not working at all. If I add the flag Intent.FLAG_ACTIVITY_SINGLE_TOP then onNewIntent is being called.

notificationIntent = new Intent();
notificationIntent.setAction(AppConstants.ACTION_ACTIVITY);
notificationIntent.putExtra("key", value);
int requestID = (int) System.currentTimeMillis();

mBuilder.setContentIntent(PendingIntent
                    .getBroadcast(context, requestID, notificationIntent, 
                                  PendingIntent.FLAG_UPDATE_CURRENT));

onReceive

  Intent intent = new Intent(context, Activity.class);
  intent.putExtra("key", value);
  //IF I ADD FLAG_ACTIVITY_SINGLE_TOP IT WORKS
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  context.startActivity(intent);

Answer

Roadblock picture Roadblock · Feb 19, 2015

Try using flags as follows for the intent.

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

And for Pending intent use PendingIntent.FLAG_UPDATE_CURRENT