首页 > 解决方案 > 在没有服务的情况下杀死应用程序后如何在后台线程中运行代码?

问题描述

我首先使用改造在后台线程上进行查询。onResponse然后我在回调中创建一个新线程。然后我让线程休眠 10 秒并尝试执行一些代码。当线程处于休眠状态时,我退出了我的应用程序。但是,当我在线程睡眠期间退出我的应用程序时,永远不会执行记录器。

mainService = RetrofitClient.getInstance().getRetrofit().create(MainService.class);
        mainService.getPosts().enqueue(new Callback<List<Post>>() {
            @Override
            public void onResponse(@NotNull Call<List<Post>> call, @NotNull Response<List<Post>> response) {
                //Running on main thread

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        //This code is never executed. I don't see it in the logcat.
                        Log.d(TAG, "onCreate: Background thread is still running -- " + Thread.currentThread().getName());

                    }
                }).start();
            }

            @Override
            public void onFailure(@NotNull Call<List<Post>> call, @NotNull Throwable t) {
                Log.e(TAG, "onFailure: Call failed", t);
            }
        });

为什么Log.d(TAG, "onCreate: Background thread is still running -- "....即使它在单独的线程上运行也不执行?

这是我正在尝试做的一个简化示例。在我的另一个项目中,在进行改造调用后,即使用户关闭应用程序,我也想将数据保存到 SQLite。但在这个例子中,我试图找出记录器没有被执行的原因。

标签: javaandroidmultithreading

解决方案


当线程处于休眠状态时,我退出了我的应用程序。

在许多(大多数?)设备上,这将终止您的进程,尤其是在您没有运行服务的情况下。终止您的进程会终止您的所有线程。

在没有服务的情况下杀死应用程序后如何在后台线程中运行代码?

WorkManager如果不需要立即完成工作,您可以使用 将工作排入队列。


推荐阅读