无法从 Android 9 或更高版本中的 BroadcastReceiver 启动 activity

Can't start the activity from the BroadcastReceiver in Android 9 or later

我无法从 Android 9 or later 中的 Broadcastreceiver 启动 activity。我知道这可能是重复的问题,但我没有得到解决方案,所以问。

这是我的代码:

Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

请帮帮我

当我在带有 Android 10 的模拟器上尝试 运行 您的代码时,我得到以下 Logcat 条目:

2019-12-30 19:26:11.579 2048-2096/system_process I/ActivityManager: Start proc 5504:com.example.broadcastreceivertest/u0a133 for broadcast {com.example.broadcastreceivertest/com.example.broadcastreceivertest.MyReceiver}

2019-12-30 19:26:11.695 5504-5504/com.example.broadcastreceivertest E/TEST: onReceive()

2019-12-30 19:26:11.730 2048-5522/system_process I/ActivityTaskManager: START u0 {flg=0x10000000 cmp=com.example.broadcastreceivertest/.MainActivity} from uid 10133

2019-12-30 19:26:11.738 2048-5522/system_process W/ActivityTaskManager: Background activity start [callingPackage: com.example.broadcastreceivertest; callingUid: 10133; isCallingUidForeground: false; isCallingUidPersistentSystemProcess: false; realCallingUid: 10133; isRealCallingUidForeground: false; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; isBgStartWhitelisted: false; intent: Intent { flg=0x10000000 cmp=com.example.broadcastreceivertest/.MainActivity }; callerApp: ProcessRecord{5ddbd7 5504:com.example.broadcastreceivertest/u0a133}]

2019-12-30 19:32:12.313 2048-2095/system_process I/ActivityManager: Killing 5504:com.example.broadcastreceivertest/u0a133 (adj 985): empty #17

有趣的部分是

W/ActivityTaskManager: Background activity start

设备 运行 Android 10(API 级别 29)及更高级别 Restrictions on starting activities from the background。这意味着您不能再从 BroadcastReceiver 开始 Activity。建议改为使用通知,以便用户可以通过点击通知来启动 Activity

此行为有一些例外情况(请参阅链接页面)。

一个简单的方法可能是添加

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

到您的清单文件。 (注意:通过 Android Studio 安装应用程序时,您必须在安装应用程序后手动授予权限)

也就是说,切换到显示通知可能更明智 - 这取决于您的用例和分发渠道。

因为 "problem API levels" 29 和更高版本甚至可以显示 full screen notification,考虑显示 Activity/ 在 onReceive() 中显示通知,具体取决于设备的 android 版本。