I'm first making a query on a background thread using retrofit. Then I create a new thread in the onResponse
callback. I then sleep the thread for 10 seconds and try to execute some code. While the thread is sleeping, I exit my app. However the logger is never executed when I exit my app during the thread sleep.
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);
}
});
Why isn't the Log.d(TAG, "onCreate: Background thread is still running -- "....
executed even though it's running on a separate thread?
This is a simplified example on what I'm trying to do. In my other project, after I make the retrofit call, I want to save the data to SQLite even if the user closes the app. But in this example, I'm trying to figure out the reason why the logger is not being executed.
CodePudding user response:
While the thread is sleeping, I exit my app.
On many (most?) devices, that will terminate your process, particularly if you do not have a service running. Terminating your process terminates all your threads.
How to run code in background thread after app is killed without Service?
You could enqueue the work using WorkManager
, if it is not essential that the work be done right away.