java - 在没有服务的情况下杀死应用程序后如何在后台线程中运行代码?
问题描述
我首先使用改造在后台线程上进行查询。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
如果不需要立即完成工作,您可以使用 将工作排入队列。
推荐阅读
- javascript - 在 NodeJS 应用程序中加载 npm 包时如何解决“未定义模块”错误
- postgresql - PostgreSQL 中一对多两边不为空
- asp.net-ajax - ASP .NET AJAX TabContainer - 在选定选项卡中的文本下划线
- postgresql - 如何将字符串转换为sql语法
- jquery - 没有响应局部视图的点击
- r - 如何使用 dplyr 管道在指定行之后重命名数据框中的所有列
- .net-core - HttpClient 和 WebClient 请求/响应不适用于具有 DefaultCredentials 的 Intranet
- sql - HIVE 中的 Distinct 保留所有变量
- php - how to implement discount value in invoice using jQuery
- python - 创建 Spark Session 抛出异常回溯