【问题标题】:How to gracefully shut down all activities and close all running threads in an Android app?如何优雅地关闭 Android 应用程序中的所有活动并关闭所有正在运行的线程?
【发布时间】:2019-06-20 22:44:11
【问题描述】:

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

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

即使在我认为我应该退出后仍继续发出请求,这会导致服务器出错。

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

【问题讨论】:

    标签: java android multithreading threadpool terminate


    【解决方案1】:

    您可以将轮询代码包装在 Service 中。然后可以使用停止此服务

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      相关资源
      最近更新 更多