从广播接收器启动Activity

3

我有以下代码来从扩展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..."));

BroadcastReciever是在manifest中注册的,我设置了INTERNET权限:

<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>

日志确认在调用startActivity()之前已设置了FLAG_ACTIVITY_NEW_TASK。尽管如此,我仍然遇到了可怕的"Calling startActivity()... requires the FLAG_ACTIVITY_NEW_TASK flag...错误提示。 非常感谢您提供任何线索。

你尝试过使用 Intent.createChooser(emailIntent, "发送邮件...").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 吗? - sandrstar
http://stackoverflow.com/questions/9771290/email-composer-in-android - RobinHood
调用startActivity包括createChooser()。 - Aharon Manne
3个回答

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

通过appContext,您可以启动一个“普通”的Activity。这里有一个示例

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();
        }
    }

所以将FLAG_ACTIVITY_NEW_TASK添加到选择器Intent而不是发送者!

0

将您的代码从emailIntent.setType("plain/text");更改为emailIntent.setType("text/plain");


0

尝试添加以下标志

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

当您启动活动时,请确保使用context.getApplicationContext(),如下所示:

context.getApplicationContext().startActivity(intent);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接