繁体   English   中英

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

[英]How to run code in background thread after app is killed without Service?

我首先使用改造在后台线程上进行查询。 然后我在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。 但是在这个例子中,我试图找出记录器没有被执行的原因。

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

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

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

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

暂无
暂无

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

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