Can An Intentservice Run Indefinitely?
Solution 1:
The IntentService
is actually a pretty small class which wraps a Handler, the problem being that after an Intent has been handled it calls stopSelf()
.
Removing that single line gives you an IntentService which needs to be explicitly stopped:
publicabstractclassNonStopIntentServiceextendsService {
private String mName;
privatevolatile Looper mServiceLooper;
privatevolatile ServiceHandler mServiceHandler;
publicNonStopIntentService(String name) {
super();
mName = name;
}
privatefinalclassServiceHandlerextendsHandler {
publicServiceHandler(Looper looper) {
super(looper);
}
@OverridepublicvoidhandleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
// stopSelf(msg.arg1); <-- Removed
}
}
@OverridepublicvoidonCreate() {
super.onCreate();
HandlerThreadthread=newHandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = newServiceHandler(mServiceLooper);
}
@OverridepublicvoidonStart(Intent intent, int startId) {
Messagemsg= mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return START_STICKY;
}
@OverridepublicvoidonDestroy() {
mServiceLooper.quit();
}
@Overridepublic IBinder onBind(Intent intent) {
// TODO Auto-generated method stubreturnnull;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/protectedabstractvoidonHandleIntent(Intent intent);
}
Solution 2:
IntentService
is extended from standard Service
class, so I don't see why it shouldn't be done this way. In fact I will do it this way too. ;)
Solution 3:
If you don't have much work to do in the service you could just extend a regular service. Return null in the onBind() and receive commands in onStartCommand() which returns START_STICKY.
Solution 4:
You need to create a Service
and bind
to your service for preventing it to stop. See the docs.
The service that will be started with bindService()
will run until no Activity is still bound to it.
Post a Comment for "Can An Intentservice Run Indefinitely?"