根据我的理解,当IntentService的当前请求完成时,它将被停止。
考虑以下场景,我将每隔100ms触发一个对IntentSerivce的请求,该请求的处理时间将为90ms。
因此,对于每个my request - startSerivce调用,服务将被调用,90ms之后(一旦处理完成),IntentServicee的onDestroy将被调用。
我想让这个IntentServicee一直运行到我说停止。这有可能吗?
假设我将在我的服务中执行以下操作
response
步骤1对我的所有请求都是通用的,所以我认为我可以在服务初始启动时执行一次,然后根据请求在HandleIntent中执行3-6步。
发布于 2012-03-30 21:44:49
IntentService实际上是一个很小的类,它包装了一个Handler,问题是在处理完一个意图之后,它会调用stopSelf()。
删除这一行将生成一个需要显式停止的IntentService:
public abstract class NonStopIntentService extends Service {
private String mName;
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
public NonStopIntentService(String name) {
super();
mName = name;
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
// stopSelf(msg.arg1); <-- Removed
}
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return START_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
/**
* 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)}.
*/
protected abstract void onHandleIntent(Intent intent);
}发布于 2011-11-05 19:53:19
IntentService是从标准Service类扩展而来的,所以我不明白为什么不应该这样做。事实上,我也会这样做的。;)
发布于 2015-01-26 04:58:34
如果你在服务中没有太多的工作要做,你可以只扩展一个常规的服务。在onBind()中返回null,在返回START_STICKY的onStartCommand()中接收命令。
https://stackoverflow.com/questions/6841212
复制相似问题