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

问题描述 投票:1回答:1

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

这是我的代码:

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

请帮助我。

android broadcastreceiver
1个回答
0
投票

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

2019-12-30 19:26:11.579 2048-2096 / system_process I / ActivityManager:启动proc 5504:com.example.broadcastreceivertest / u0a133进行广播{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:从uid 10133开始u0 {flg = 0x10000000 cmp = com.example.broadcastreceivertest / .MainActivity}

2019-12-30 19:26:11.738 2048-5522 / system_process W / ActivityTaskManager:后台活动开始[callingPackage:com.example.broadcastreceivertest; CallingUid:10133; isCallingUidForeground:否; isCallingUidPersistentSystemProcess:假; realCallingUid:10133; isRealCallingUidForeground:否; isRealCallingUidPersistentSystemProcess:假; originatingPendingIntent:空; isBgStartWhitelisted:否;目的:目的{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):空#17

有趣的部分是

W / ActivityTaskManager:后台活动开始

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

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

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

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

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

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

由于可能甚至在“问题API级别” 29和更高版本中显示full screen notification,因此请考虑显示Activity /在onReceive()中显示通知,具体取决于设备的Android版本。

© www.soinside.com 2019 - 2024. All rights reserved.