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

时间:2019-01-27 22:16:59

标签: java android multithreading threadpool terminate

此刻,在我的每一项活动中,我都有这种方法:

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

,还有这个:

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

它们由以下退出按钮触发:

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

我确定关闭方法不正确的一件事是,我有以下代码:

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

即使我认为后,它仍会继续发出请求,这会导致服务器错误。

如何确保所有线程正常停止并且应用程序以正确的方式关闭?

1 个答案:

答案 0 :(得分:1)

您可以将轮询代码包装在Service中。然后可以使用

停止该服务
Intent intent = new Intent(MainActivity.this, MyService.class); 
stopService(intent);  

在服务内部,您可以覆盖onDestroy()来清理资源。