Any solution which uses Threads, Runnables, AsyncTask or otherwise with a Service will have a common problem.
The Service will block the calling Activity until after the service is started. And thus doesn't effectively thread the Service in certain cases.
The solution to this is to use the IntentService subclass.
Example of how to implement:
public class MyCustomService extends IntentService
{
private DatabaseAdapter mAdapter;
public MyCustomService() {
super("MyCustomService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "MyCustomService Started", Toast.LENGTH_LONG).show();
// Don't let this service restart automatically if it has been stopped by the OS.
return START_NOT_STICKY;
}
@Override
protected void onHandleIntent(Intent intent)
{
Toast.makeText(this, "MyCustomService Handling Intent", Toast.LENGTH_LONG).show();
// INSERT THE WORK TO BE DONE HERE
}
}
onCreate() and onDestroy can also be overriden so long as super.onWhatever() is called inside them.