Starting Activity from BroadcastReceiver

2019-02-18 17:46发布

问题:

I have the following code to send an e-mail from a class that extends BroadcastReceiver:

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
S2Mconfig s2m = new S2Mconfig();
Log.d(TAG, "Create Intent for mail to " + address);
emailIntent.setType("plain/text");
emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, s2m.read(thisContext));
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, address);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
Log.d(TAG, String.format("Sending mail %s", emailIntent.toString()));
thisContext.startActivity(Intent.createChooser(emailIntent, "Send mail..."));

The BroadcastReciever is registered in the manifest, and I set the INTERNET permission:

<uses-permission android:name="android.permission.INTERNET" />...

<receiver android:name=".SmsReceiver" android:exported="true" > 
        <intent-filter android:priority="1000"> 
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            <action android:name="android.provider.Telephony.MMS_RECEIVED" />
        </intent-filter>
    </receiver>

The log confirms that the FLAG_ACTIVITY_NEW_TASK was set before the call to startActivity(). Despite all this, I still get the dreaded "Calling startActivity()... requires the FLAG_ACTIVITY_NEW_TASK flag... Any clue would be greatly appreciated.

回答1:

@Override
public void onReceive(Context context, Intent intent){
    Context appContext = context.getApplicationContext();

and with appContext you can start a "normal" Activity. Described here is an example

public void sendNotificationEmail(String emailBody) {
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setType("text/html");
        emailIntent.putExtra(Intent.EXTRA_EMAIL, notificationRecipients);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "MyAppName Error");
        emailIntent.putExtra(Intent.EXTRA_TEXT, emailBody);
        Intent emailChooser = Intent.createChooser(emailIntent, "An error has occurred! Send an error report?");
        emailChooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(emailChooser);
        } catch (ActivityNotFoundException e) {
            // If there is nothing that can send a text/html MIME type
            e.printStackTrace();
        }
    }

So add the FLAG_ACTIVITY_NEW_TASK to the chooser Intent and not the sender!



回答2:

Try to add following flags also

intent.addFlags(
          Intent.FLAG_ACTIVITY_NEW_TASK
        | Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP);

And when you start your activity, make sure your are using context.getApplicationContext() like

context.getApplicationContext().startActivity(intent);



回答3:

Change your code from emailIntent.setType("plain/text"); to emailIntent.setType("text/plain");