【发布时间】:2016-08-09 14:34:42
【问题描述】:
当操作系统终止应用程序时,我的警报被终止。我认为这是警报的要点之一,即使操作系统杀死了应用程序,它也会继续运行?我使用“./adb shell dumpsys alarm”命令检查警报的生命周期,每次操作系统杀死我的应用程序时,警报也消失了。我如何启动闹钟:
public static void startLocationAlarm(Context context){
if(ActivityLifecycleHandler.isApplicationInForeground()) {
return; // If App is in foreground do not start alarm!
}
String alarm = Context.ALARM_SERVICE;
AlarmManager am = ( AlarmManager ) context.getSystemService( alarm );
Intent intent = new Intent(locationBroadcastAction);
PendingIntent pi = PendingIntent.getBroadcast( context.getApplicationContext(), 0, intent, 0 );
int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long interval = ONE_MINUTE;
long triggerTime = SystemClock.elapsedRealtime() + interval;
am.setRepeating(type, triggerTime, ONE_MINUTE, pi );
}
为了添加更多上下文,我尝试在后台的服务(不是 IntentService)中进行一些定位操作。这是我的接收器。使用 Wakeful 是因为我不想在服务完成之前将其终止。
public class LocationBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent ) {
Intent myIntent = new Intent( context, LocationServiceAlarmOwnGoogleClient.class );
//context.startW( myIntent );
LocationBroadcastReceiver.startWakefulService(context, myIntent);
}
}
有关更多信息:我在 OnStart 方法中取消了几个活动的警报,用户可以在后台返回这些活动。我不知道这是否会导致这种奇怪的行为?这是我的取消方法:
public static void stopLocationAlarm(Context context){
Intent intent = new Intent(locationBroadcastAction);
PendingIntent sender = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
【问题讨论】:
-
这是默认行为
-
“每次操作系统杀死我的应用程序,警报也消失了”——请详细解释一下“操作系统杀死我的应用程序”是什么意思。
-
@Shaishav Aaah,好的。我认为即使应用程序被操作系统杀死,警报也应该继续存在。即使操作系统杀死它,我怎样才能让它继续存在?
-
我要指出 Commonsware 的另一个答案:stackoverflow.com/questions/9101818/…
-
@CommonsWare 当我将我的应用程序放在后台一段时间系统会杀死它(或者这就是我认为它所做的,因为它突然在 Android Studio 中显示为 DEAD)。我想它这样做是为了节省资源或其他东西。发生这种情况时,警报会被取消。如果用户杀死它,我不介意警报被取消。
标签: android alarmmanager