0

i am playing with SQLite and SQL server databases to sync each other. I enclosed separate table updation in separate methods. it can execute successfully from the main thread but it takes long time. how can i enclose those methods in asynctask ?

say I have 4 methods, for my four tables which syncs data between server and sqlite.... when i am running all these methods under main UI thread it takes time to complete those operations. So my question is how o import those methods into doInBacckground of async task.

1 Answers1

1

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:

  1. http://javatechig.com/android/creating-a-background-service-in-android
  2. http://www.101apps.co.za/articles/using-an-intentservice-to-do-background-work.html
  3. http://www.mysamplecode.com/2011/10/android-intentservice-example-using.html

Hope this will help you.

Md. Sajedul Karim
  • 7,031
  • 3
  • 56
  • 81