Issue
I have a logic in my application so that when OnStop() happens I save a file to the storage. However, if the file is large and I close application by swiping from Recents Tab my application is shut down before my file is saved. So it opens file then app dies and the file remains empty. Is that normal behaviour or the task killer on my phone is overplaying? Should I create a service to save a file certainly?
example code:
@Override
public void onStop() {
try (FileWriter writer = new FileWriter(path)) {
if (veryLargeFile == null) {
return;
}
String s = veryLargeFile.toString();
Log.d(TAG, "this message is shown");
writer.write(s);
Log.d(TAG, "this message is not shown");
writer.flush();
} catch (IOException ex) {}
super.onStop();
}
Example 2:
@Override
public void onPause() {
try (FileWriter writer = new FileWriter(path)) {
if (veryLargeFile == null) {
return;
}
String s = veryLargeFile.toString();
Log.d(TAG, "this message is shown");
writer.write(s);
Log.d(TAG, "this message is not shown");
writer.flush();
} catch (Exception ex) {
Log.d(TAG, "this message is not shown");
}
super.onPause();
}
Solution
This makes sense, I presume the file save will happen asynchronously so you have no guarantee that it will finish before the application is torn down completely.
As some people in the comments have already pointed out, WorkManager
is probably your best solution here and is able to defer asynchronous tasks for the system to manage, so will be able to run even if your app finishes.
There is some nice documentation here: Schedule tasks with WorkManager.
Edit
If the code you're trying to run is synchronous, it should still be able to complete during onStop
(post Honeycomb) or onPause
due to the lifecycle methods being (as the documentation describes it) "unkillable".
However this is still no guarantee if your app is force stopped or crashes whilst finishing and as the lifecycle documentation states:
Keep in mind that under extreme memory pressure the system can kill the application process at any time.
So I would presume that this is an issue with the memory management on your specific device which causes the app to be killed prematurely. If this is the case then I would consider using a better persisting method, either on a regular interval or during your apps foreground time if it is essential.
Answered By - Henry Twist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.