在退出android中的应用程序后给定的延迟间隔后,处理程序postdelayed不会被解雇?

时间:2015-05-23 15:13:03

标签: android handler runnable postdelayed

代码段:

Handler handler= new Handler();
handler.postDelayed(networkRunnable,
                10000);

/**
 * A runnable will be called after the 10 second interval
 */
Runnable networkRunnable= new Runnable() {
    @Override
    public void run() {
        //Not fired if I quit the app before 10 seconds after 1 second. 
    }
};

设置处理程序帖子在10秒后延迟触发。如果我在1到10秒之间退出应用程序,则运行方法永远不会调用。

请帮我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:2)

Android运行时积极地管理进程生命周期,在其入口点关闭时(例如,当最后一个活动完成时)销毁进程。话虽如此,我还不知道上面的代码可以在没有额外逻辑的情况下可靠地执行回调的任何执行环境。

如果您希望确定要激活呼出,则需要使用Android核心注册服务并使用服务线程的处理程序来安排呼出。 Android将(通常)保持服务运行,您的标注将在稍后触发。然后,您还应该在呼出中取消注册该服务以释放系统资源。

答案 1 :(得分:0)

为了达到这个目的,我使用了一个AlarmManager而不是处理程序,它现在正在使用,这是我使用的代码的摘录:

@Override   
protected void onHandleIntent(Intent intent) {
    Log.d(Constants.TAG, "onHandleIntent");
    ...
    restartService();
    Log.d(Constants.TAG, "finish");   
}

private void restartService() {
   AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   Intent queryIntent = new Intent(context, ServiceClass.class);
   PendingIntent pendingQueryIntent = PendingIntent.getService(context, 0, queryIntent,
    PendingIntent.FLAG_UPDATE_CURRENT);
    // schedule the intent for future delivery
    alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + Constants.RESTART_TIME, pendingQueryIntent);
}

通过这种方式,我可以重新启动服务,无论用户是否使用主页,后退或从最近的应用程序轻扫来关闭应用程序,它停止工作的唯一方法是使用强制应用程序停止。

希望有所帮助