Executing Asynchronous Task From Service In Android
Solution 1:
AsyncTask
always works on main/UI thread. And if your Service
is running under a different process then it is not associated to main thread, that's why you cant use AsyncTask
in Service
.
In your case, you are encouraged to use HandlerThread
, Looper
and Handler
to perform heavy lifting on separate thread.
Read this article.
Solution 2:
you can use HandlerThread
in your service for doing background work like:
publicclassServicewithHandlerThreadextendsService {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
privatefinalclassServiceHandlerextendsHandler {
publicServiceHandler(Looper looper) {
super(looper);
}
@OverridepublicvoidhandleMessage(Message msg) {
while (true) {
synchronized (this) {
try {
//YOUR BACKGROUND WORK HERE
} catch (Exception e) {
}
}
}
stopSelf(msg.arg1);
}
}
@OverridepublicvoidonCreate() {
// Start up the thread running the service.HandlerThreadthread=newHandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = newServiceHandler(mServiceLooper);
}
@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
Messagemsg= mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_STICKY;
}
@Overridepublic IBinder onBind(Intent intent) {
returnnull;
}
}
Solution 3:
There's a few options. If you need communication between your task and say, an activity, AsyncTask would be your best best, IMO. If you just need to "fire and forget", IntentService can be of help.
Remember, a service still runs on the main thread. If you need to do anything that requires some processing or lookup such as network download/upload or SQL queries, you should move that to a new thread using on of the aforementioned classes.
Post a Comment for "Executing Asynchronous Task From Service In Android"