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

How to call onDestroy() from onStop() after a delay

例如,如果用户单击主页按钮,将调用 onPause() 和 onStop() 方法。 我想在 1 分钟后从 onStop() 方法调用 onDestroy(),除非用户返回应用程序(调用 onResume() 和 onStart() 方法)。

我尝试实现定时器: 它失败了,说如果 Looper 没有实现它就不能调用 onDestroy。 当我实现 Looper 时,永远不会调用 onDestroy() 方法。

也许从 on​​Stop() 调用 onDestroy() 不是一件好事,还有另一个 "clean" 解决方案可以实现我想要的行为。我只想在 100 万没有用后终止该应用程序。 在此情况下,请提出。

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

不要直接调用 onDestroy() ,而是在你想要的时间段后调用 finish() 并支持您提到的场景,如果用户恢复了 activity,请确保不要杀死 activity 这是我为您编写的一段代码。 如果在 1 秒内没有恢复,activity 将自杀;

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");
}

这个答案主要是从上面的 Abdelrahman post 那里得到启发。 每次我离开我的应用程序时,我只是调整了一些东西来重新初始化延迟计数器。

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 快速准确的回答。 如果此处未正确完成某些操作,请发表评论。至少它按预期工作...