我首先使用更新对后台线程进行查询。然后在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。但是在这个例子中,我试图找出为什么不执行记录器。
发布于 2021-10-25 23:09:17
当线程在睡觉时,我退出我的应用程序。
对许多人(大多数?)设备,这些设备将终止进程,特别是在没有运行服务的情况下。终止进程将终止所有线程。
如何在没有服务的情况下杀死应用程序后在后台线程中运行代码?
如果不需要立即完成工作,则可以使用WorkManager对工作进行排队。
https://stackoverflow.com/questions/69715573
复制相似问题