android应用程序退出的回调方法,应用程序从android中的最新应用程序中被杀死时的回调侦听器...
我终于自己弄明白了.我使用了服务和报警管理器的组合.每次我想处理强制关闭场景时,我都会启动一个运行无限循环的服务.这个循环每隔15秒就会迭代一次.在循环中,我设置了一个距离当前时间20秒的警报.现在,如果循环的下一次迭代发生,则更新警报并在新的当前时间之后重置为20秒.这样,只有当用户没有通过调用stopService()方法销毁服务时,才会触发警报.public class MyIntentSe
我终于自己弄明白了.我使用了服务和报警管理器的组合.每次我想处理强制关闭场景时,我都会启动一个运行无限循环的服务.这个循环每隔15秒就会迭代一次.在循环中,我设置了一个距离当前时间20秒的警报.现在,如果循环的下一次迭代发生,则更新警报并在新的当前时间之后重置为20秒.这样,只有当用户没有通过调用stopService()方法销毁服务时,才会触发警报.
public class MyIntentService extends IntentService {
public MyIntentService() {
super("My IntentService");
}
private boolean stopped = false;
private Thread runningThread;
private static MyIntentService mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = MyIntentService.this;
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
stopped = false;
runningThread = Thread.currentThread();
while(!this.stopped) {
Intent intent = new Intent("Your_Custom_Broadcast_Action");
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent broadcastIntent = PendingIntent.getBroadcast(WifiService.this, CLEAN_UP_ALARM_REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);
}
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
mInstance = null;
if (runningThread != null) {
runningThread.interrupt();
}
}
public void stopService() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent broadcastIntent = PendingIntent.getBroadcast(WifiService.this, CLEAN_UP_ALARM_REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(broadcastIntent);
stopped = true;
if (runningThread != null)
runningThread.interrupt();
}
public static MyIntentService getActiveInstance() {
return mInstance;
}
}
更多推荐
所有评论(0)