gpt4 book ai didi

android - 从 BroadcastReceiver 启动 Activity

转载 作者:太空宇宙 更新时间:2023-11-03 13:29:22 26 4
gpt4 key购买 nike

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

BroadcastRecievermanifest中注册,我设置了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>

日志确认 FLAG_ACTIVITY_NEW_TASK 是在调用 startActivity() 之前设置的。尽管如此,我仍然遇到可怕的 “调用 startActivity()...需要 FLAG_ACTIVITY_NEW_TASK 标志...任何线索将不胜感激。

最佳答案

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

并且使用 appContext,您可以启动“正常” Activity 。说明here是一个例子

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 而不是发送者!

关于android - 从 BroadcastReceiver 启动 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15218476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com