在后台运行一段时间后关闭应用程序

Close app after some time in background

我正在寻找一种方法,可以在 android 应用程序未处于焦点状态一段时间后将其关闭。例如,如果用户改为打开另一个应用程序,则该应用程序应在 5 分钟后退出。我试过使用 runnable 并创建一个线程。但是当应用程序处于后台时,这些方法似乎不起作用(我不确定它们是否暂停)。那么应用不在焦点时如何关闭呢?

对于那些想知道我想要这样做的原因是应用程序包含一些关于用户的敏感数据的人,所以我想确保在他们不使用它时所有这些数据都被清除。

获取您的应用程序的进程 ID,并使用 onDestroy() 方法终止该进程

@Override
public void onDestroy()
{
   super.onDestroy();

   int id= android.os.Process.myPid();

   android.os.Process.killProcess(id);
}

参考- how to close/stop running application on background android

编辑 - 将其与 AlarmManager 一起使用

我建议在 onPause()onStop() 回调中调用 finish()TimerTask 将无法在 onPause() 中存活下来,并且从表面上看,服务不会出现,为您提供选择。也许你可以启动一个服务,让服务运行的线程休眠,然后在休眠定时器到期后终止你的应用程序的进程。

或者,您可以只实施一些安全库来帮助保护来自其他应用程序的数据。

Here 是 Google 服务 link。

类似这样的方法可能有效:

activity里面的字段class:

private Thread t = null;

里面 onResume():

if(t!=null) {
    if(t.isAlive()) {
        t.interrupt();
        t.join();
    }
    t=null;
}

里面 onPause():

t = new Thread() {
    public void run() {
            try {
                sleep(5*60*1000);
                // Wipe your valuable data here
                System.exit(0);
            } catch (InterruptedException e) {
                return;
            }
    }.start();
}

您尝试做的事情的根本问题是,当您的 Activity 处于后台时,它可能根本不存在于内存中。 Android 框架可能已经破坏了 activity 实例,甚至是 运行 所在的进程。所有存在的可能是您在 onSaveInstanceState(...) 中保存的持久状态和屏幕截图最近的应用程序列表。可能没有什么可以让你拿来参考杀掉的

to call finish() in onPause() will prevent your activity from running in the background at all, but this is the closest you can get to what you want. You probably only want to do this when isChangingConfigurations() is false. But even when all your app's activities are finished, Android may keep the process and Application instance around to avoid recreating them later. So you may also want to use 杀死进程。在 onPause() 中执行此操作,因为 activity 可能会在不调用 onDestroy().

的情况下被销毁