应用程序从android中的最新应用程序中被杀死时的回调侦听器
作者:互联网
让我直截了当地谈谈我的问题.
有一个古老的类似问题:
Continue Service even if application is cleared from Recent app.在继续之前请先通过link.
在完全销毁应用程序之前,我必须将一些数据保存到本地数据库.
我有以下服务的onTaskRemoved()方法的问题:
每次从最近的应用程序屏幕停止应用程序(以及服务)时,都不会触发onTaskRemoved()方法.
>即使每次调用onTaskRemoved(),该方法也不会完全执行.我的意思是如果方法中有20个语句,则只执行5或10个语句,之后方法会中断.就像我有20个System.out.println()语句,而不仅仅是5或10或12(任意随机数)语句打印和方法中断之后.
所以我可以依靠onTaskRemoved()方法来清理应用程序获取的资源.
这是我的应用程序发布的阻塞问题.我尝试了每一招.就像在堆栈中至少有一个活动(我称之为GhostActivity)一样,如果应用程序从最近的应用程序屏幕中被杀死,我们可以在onDestroyed()方法中清理活动.调用了onDestroyed(),但它与onTaskRemoved()方法完全相同.
我几周以来一直坚持这个问题而且非常讨厌.如果有人有任何解决方案,请告诉我.
解决方法:
我终于自己弄明白了.我使用了服务和报警管理器的组合.每次我想处理强制关闭场景时,我都会启动一个运行无限循环的服务.这个循环每隔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;
}
}
标签:android,android-service,service,background-service 来源: https://codeday.me/bug/20190710/1427103.html