【发布时间】:2021-12-11 09:10:30
【问题描述】:
我首先使用改造在后台线程上进行查询。然后我在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。但在这个例子中,我试图找出记录器没有被执行的原因。
【问题讨论】:
-
“我退出了我的应用程序”——确切地说是什么意思?你做了系统返回导航吗?你做了系统HOME导航吗?您是否将应用程序从概览屏幕(最近的任务列表)中滑出?你还做了别的吗?
-
我将应用从最近任务列表中滑出i.imgur.com/KUtRYYb.png
标签: java android multithreading