(在将此问题标记为重复之前,请注意,我在特定的API级别(API R)中遇到此问题,该应用程序会在R以下的其他API级别上显示正常的预期工作行为)。
在Pixed 3a API R
上运行应用程序时
我正在通过构建基本的警报应用程序尝试使用android中的警报管理器。我有一个AlarmPageActivity,尝试从我的自定义广播接收器(AlarmReceiver.java
)启动
我的MainActivity中有代码,可以使用Alarm Manager设置警报。警报响起时,待处理的意图将转到AlarmReceiver
类,在该类中,我尝试使用context.startActivity(context, alarmIntent)
启动活动。
问题:[在您去那里之前,是的,我需要适当的标志(Intent.FLAG_ACTIVITY_NEW_TASK
)]。当我设置警报时间并保持应用程序打开时,AlarmPageActivity(当警报关闭时应该弹出的活动)启动,并且该应用程序执行正常的行为。但是,当我设置时间并关闭应用程序(onDestroy()
)时,代码会一直跟踪到AlarmReceiver.java
(我的广播接收器),铃声开始播放,但是我的AlarmPageActivity没有显示(实际上,即使是onCreate()
方法不执行)。在“日志/运行”窗口中也不会显示任何错误。我尝试更改所有内容,从待处理的Intent参数,到将新的活动标志添加到Intent对象等,但是没有任何效果!您可以在下面的代码中看到,没有语法错误应阻止该代码通过广播接收器启动新活动(当用户不在应用程序外部时)。
我面对这个问题将近2天。我阅读了互联网上有关从广播接收器类开始一项活动的每篇文章/帖子。但这是行不通的,我感到非常沮丧。然后,我奇迹般地想到了为什么不尝试在其他模拟器上运行该应用程序。你猜怎么着?有效。 sigh...
我一直以为自己做错了什么,或者我的代码很乱,因为我只是android studio中的初学者。但是我几乎不知道我的代码在所有时间内都是正确的。
在Pixed 3a API 26
上运行应用程序时
该应用程序显示正常的预期行为。即使在onDestroy()之后,BroadCast接收器也会接收并启动带有铃声的AlarmPageActivity :)
我的问题:这是与在运行API R的仿真器设备上不起作用,但现在可以在API 26中运行的代码相同(我没有更改/添加任何其他内容)。有人可以解释为什么它不起作用吗?我真的很感激。也许我的代码在某种程度上与API R不兼容...谁知道?开导我!
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
...
other code...
...
// Alarm manager code ----------------------------------------
alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 56);
calendar.set(Calendar.SECOND, 0);
long startTime = calendar.getTimeInMillis();
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
final PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(this, 0,
alarmIntent, 0);
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, startTime, alarmPendingIntent);
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.d("asdfasdf", "BroadcastReceiver (alarmReceiver) activity reached");
Intent alarmIntent = new Intent(context.getApplicationContext(), AlarmPageActivity.class);
alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarmIntent);
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
// ringtone code ...
ringtone.play();
Log.d("asdfasdf", "Reached end of alarmReceiver ");
}
} // mind the wrong indenting here
AlarmPageActivity.java
has the default empty activity code...
是的,我知道我不应该从广播接收器运行活动,因为它不应该执行耗时超过10秒钟的繁重任务,但是我只是想看看它的样子,然后再对该代码进行改进。
最佳答案
我认为从android 10及更高版本开始不起作用。请阅读有关Restrictions on starting activities from the background的更多详细信息。在这种情况下,尝试请求permisison SYSTEM_ALERT_WINDOW