Stop A Thread Downloading Images When Activity Finishes
Solution 1:
I can suggest simpler&safer approach to handle this
Use common value across your app; SharedPreferences or inside Application context Key=IsStopDownload Value= True / False
part.1) in Application context (MyApplication)
privateboolean isAppActive = false;
publicvoidsetAppState(Context context, boolean state) {
isAppActive = state;
// note: you can also store this in SharedPreferences
}
publicbooleangetAppState(Context context) {
return isAppActive;
// note: you can also load this from SharedPreferences
}
part.2) Activity onResume and onPause are the guaranteed places to identify state of your activity.
onResume -> activity is active onPause -> activity is not active
part.3) let your thread check the activity state and if not active, it can stop itself, thats safer then making external interrupt. threads can act weird when interrupted from outside, it is safer to break the loop from inside.
e.g.
((MyApplication)context.getApplicationContext()).getAppState(context);
if thats false, thread stops itself
hope this helps...
--- Social Coding @AspiroTV
Solution 2:
When user will switch the activity , this one will not destroyed but paused so trying your code is onPause() might work .
Solution 3:
First of all, you're probably much better using an AsyncTask than a Thread
, so, personally, I wouldn't use a Thread
at all. In my humble opinion and small experience, in that situation where you're using them, they grow and grow until you have spaguetti code.
And second, as Dr. Nik said, this task is typically better served using a Service. It's is, in my opinion, the best and safer thing you can do.
I would point out several reasons why you should use one:
- The service does not need to stop because the activity goes away.
- Services are very easy and quick to implement. And the notification code for completion is also easy.
- You are downloading images, and it's always better to do the job at once if you can, to save bandwidth and connection time for the user and cache images locally. This used to be worse because today cell phones are full fledged computers. But it's always important to code for efficiency. Therefore, IMHO, you should keep the need for a connection as small/quick as possible.
- Finally, even using
AsyncTask
s inside an activity demands a tricky (simple, but still tricky) code to catch and detach the task when the Activity is going away, and a check for nulls when it's coming back. Since you're downloading images, and that can take a time and it's very possible that the user may demand an orientation change (turn the device to landscape), you will need that. Search stackoverflow for "orientation change asynctask" for examples.
There are probably other reasons, too, but those are on the top of my head right now. And of course, it's my opinion.
Post a Comment for "Stop A Thread Downloading Images When Activity Finishes"