如何在延迟后从onStop()调用onDestroy()

时间:2015-10-12 02:58:42

标签: android android-lifecycle

如果用户点击Home按钮,则会调用onPause()和onStop()方法。 我希望在1mn之后从onStop()方法调用onDestroy(),除非用户返回应用程序(调用onResume()和onStart()方法)。

我试图实现Timer: 它失败了,如果没有实现Looper,它就无法调用onDestroy。 当我实现Looper时,永远不会调用onDestroy()方法。

也许从onStop()调用onDestroy()不是好事,而另一个" clean"解决方案存在以获得我想要的行为。我只是想在1mn没用后杀死应用程序。 在这种情况下,请提议。

如果我的愿望是继续进行的好方法,你能分享一下如何实施吗?

2 个答案:

答案 0 :(得分:2)

不要直接调用onDestroy(),而是在你想要的时间之后调用finish() 并且为了支持您提到的方案,请确保在用户恢复活动时不要终止活动 这是我为你写的一段代码。 如果不在1秒钟内恢复,活动就会自杀;

boolean notResumed;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startActivity(new Intent(this,Main2Activity.class));
}

@Override
protected void onResume() {
    super.onResume();
    notResumed=false;
}

@Override
protected void onStop() {
    super.onStop();
    notResumed=true;
    Handler handler=new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(notResumed)
            finish();
        }
    },1000);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d("debug","onDestroyCalled");
}

答案 1 :(得分:-1)

这个答案主要来自上面的Abdelrahman的帖子。 每次我退出应用程序时,我只调整了一些事情来重新初始化延迟计数器。

boolean notResumed;
//Declare my Handler in global to be used also in onResume() method
Handler myHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startActivity(new Intent(this,Main2Activity.class));
}

@Override
protected void onResume() {
    super.onResume();
    notResumed=false;
    //Remove callbacks on the handler if it already exists
    if (myHandler != null) {
        //I send null here to remove all callbacks, all messages,
        //and remove also the reference of the runnable
        myHandler.removeCallbacks(null);
    }
}

@Override
protected void onStop() {
    super.onStop();
    notResumed=true;
    myHandler=new Handler();
    myHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(notResumed)
                finish();
        }
    },10000);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d("debug","onDestroyCalled");
}

再次感谢Abdelrahman Nazeer的快速而准确的答案。 如果在这里没有正确完成某些事情,请评论。至少它按预期工作......

相关问题