简体   繁体   English

如何在Android应用中正常关闭所有活动并关闭所有正在运行的线程?

[英]How to gracefully shut down all activities and close all running threads in an Android app?

At the moment, in each one of my activities I have this method: 目前,在我的每一项活动中,我都使用这种方法:

private void registerReceiverClose(){
    Activity activity = this;
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("CLOSE_ALL");
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            activity.finish();
        }
    };
    registerReceiver(broadcastReceiver, intentFilter);
}

and this one as well: 还有这个:

@Override
protected void onDestroy() {
    unregisterReceiver(broadcastReceiver);
    super.onDestroy();
}

They're triggered by the following logout button: 它们由以下注销按钮触发:

    Button logout = findViewById(R.id.logout_button);
    logout.setOnClickListener(click -> {
        Intent intent = new Intent("CLOSE_ALL");
        this.sendBroadcast(intent);
    });

One thing that I'm sure is not closing in the right way, is that I have this code: 我确定关闭方法不正确的一件事是,我有以下代码:

private static final ScheduledExecutorService pollingScheduledExecutor = Executors.newSingleThreadScheduledExecutor();

private static final Object lock = new Object();
private static ScheduledFuture<?> currentRunningTask;

public void longPoll() {
    synchronized (lock) {
        if (currentRunningTask != null) {
            currentRunningTask.cancel(true);
        }
        try {
            currentRunningTask = pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);
        } catch (Exception ignored) {
        }
    }
}

public void request() {
    Thread requestThread = new Thread(this);
    requestThread.start();
}

which continues to issue requests even after I think I should be logged out, which causes errors on the server. 即使我认为我应该注销后仍会继续发出请求,这会导致服务器错误。

How can I make sure all the threads stop gracefully and the application closes down in the right way? 如何确保所有线程正常停止并以正确的方式关闭应用程序?

You could wrapthe polling code inside of a Service . 您可以将轮询代码包装在Service中 This service can then be stopped using 然后可以使用停止该服务

Intent intent = new Intent(MainActivity.this, MyService.class); 
stopService(intent);  

Inside of the service, you can override onDestroy() to clean resources up. 在服务内部,您可以重写onDestroy()来清理资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM