简体   繁体   中英

Sending intent to activity from BroadcastReceiver

I have yet another question. I did some research into how to properly send an intent from a BroadcastReceiver to an activity. everyone suggests doing the following:

To construct an intent and use the context provided in the receiver to start that intent. However, I would always get an error when trying to do so saying

AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

So when I googled about that error, people seemed to suggest that you want to add specific flags to the intent. But even with this flags present I am getting the same error. Any help would be appreciatd.

Intent intentMain = new Intent(context.getApplicationContext(), MainActivity.class);
intentMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intentMain.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("com.hennessylabs.xxx.FROM", senderNum);
intent.putExtra("com.hennessylabs.xxx.MSG", message);
context.startActivity(intentMain);
Intent intent = new Intent(context,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

and then in manifest file in mainactivity

launchmode= singleTask

or as per your requirements, you can use some other combinations also

It looks like you are trying to start MainActivity.class from your BroadcastReceiver. That is fine. Though I don't see why you have done what you did in the 2nd and 3rd lines you provided when adding flags. Why don't you just do this:

intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

So your whole code block should look like this:

Intent intentMain = new Intent(context.getApplicationContext(), MainActivity.class);
intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("com.hennessylabs.xxx.FROM", senderNum);
intent.putExtra("com.hennessylabs.xxx.MSG", message);
context.startActivity(intentMain);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM