It is really a very very bad idea to use AsyncTasks for long running operations. Nevertheless, they are fine for short living ones such as updating a View after 1 or 2 seconds.
AsyncTasks don't follow Activity instances' life cycle. If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It's one of the reasons that it is advised to avoid AsyncTask for long running tasks.
However if your Activity goes on pause during the process, this is likely to crash so you should cancel your task in onPause() using task.cancel(true);
If you need your task to survive your activity, then you should use either a Service or a ServiceIntent. The former is a bit more complex as you have to manage its life-cycle but offers more flexibility. The second is damn straightforward so I can give you an example here:
public class MyIntentService extends IntentService{
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
// Background work in a worker thread (async)
// You could also send a broadcast if you need to get notified
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("whatever");
LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
}
}
The you can start if from your activity with this command:
Intent i = new Intent(context, MyIntentService.class);
context.startService(i);
Here is some links about Intent Service:
- http://javatechig.com/android/creating-a-background-service-in-android
- http://www.101apps.co.za/articles/using-an-intentservice-to-do-background-work.html
- http://www.mysamplecode.com/2011/10/android-intentservice-example-using.html
Hope this will help you.