I have a BroadcastReceiver that I’m using to send data to another activity which may or may not be running. I’m using the intent in my onReceive() method, and putting the data in with putExtra(). THe data gets sent to the activity, however, the activity’s onCreate() method gets called even though the activity is already running and in the foreground, so I guess it’s creating a new instance. I want to only have onResume() called, or perhaps there’s some other way I can create/start the intent if it doesn’t exist, and if it does, just have it ‘resumed’. Right now, the activity is being recreated, and I do not want this.
public void onReceive(Context context, Intent intent) {
intent.setClass(context, MyActivity.class);
intent.putExtra("message", "the data here");
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d("sending msg", "msg");
context.startActivity(intent);
}
If I do not use FLAG_ACTIVITY_NEW_TASK, a RuntimeException is throw, specifically telling me that if I want to start an activity from something that is not an activity, I must use FLAG_ACTIVITY_NEW_TASK.
I ended up rebroadcasting (internally) the parsed information that my BroadcastReceiver was getting in. The actvity, in code, registered for the event and had a small handler method in a private-created receiver. This was a good solution as I know that this activity would always be running in my case.