了解IntentService的机制?

时间:2011-11-04 21:51:33

标签: android

我试图理解IntentService类,这样我就可以构建自己的扩展,在这个扩展中我可以阻止队列随时处理所有线程。以下代码已从此处复制:http://www.google.com/codesearch#cZwlSNS7aEw/frameworks/base/core/java/android/app/IntentService.java&q=IntentService&exact_package=android&type=cs

在我的主要活动中,我有以下代码:

            Intent intent = new Intent(this,DownloadService.class);
            for(int i=0;i<filesArray.length;i++){
                 startService(intent);
             }

代码基本上为数组中的每个文件启动一个IntentService。现在我想知道IntentService类如何排队这个线程或服务,特别是我想知道如何修改IntentService类来停止&#39;结束&#39;服务并从等待处理的所有线程中清除队列。非常感谢任何帮助。它已经困扰了我很长一段时间!!!!

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    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);
        }
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    /**
     * Sets intent redelivery preferences.  Usually called from the constructor
     * with your preferred semantics.
     *
     * <p>If enabled is true,
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
     * {@link #onHandleIntent(Intent)} returns, the process will be restarted
     * and the intent redelivered.  If multiple Intents have been sent, only
     * the most recent one is guaranteed to be redelivered.
     *
     * <p>If enabled is false (the default),
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
     * dies along with it.
     */
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        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 mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

    @Override
    public IBinder onBind(Intent intent) {
        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);
}

编辑: 我试图使用IntentService逐个下载多个文件。但是,当Internet连接断开时,IntentService会卡在它正在处理的当前线程上,或者只是继续它的生命周期。我希望在互联网连接断开时终止服务的生命周期。

编辑: 我已经复制了IntentService的代码,并使用相同的代码创建了一个MyIntentService类。我对代码进行了以下更改:

    public volatile Looper mServiceLooper;
    public volatile ServiceHandler mServiceHandler;
    public String mName;
    public boolean mRedelivery;

    final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

上述变量已公开,内部类已更改为最终类。现在在扩展MyIntentService的DownloadService中,我有一个如下代码:

if(!isOnline()){
    mServiceHandler.removeMessages(0);
    mServiceLooper.quit();
    stopSelf();
}

我先检查是否有Internet连接,如果没有,那么我将从服务处理程序的队列中删除消息(假设我正确地执行了此操作),我&# 39; m停止循环,我停止服务,我不知道它停止了哪个服务。 HEELP !!

2 个答案:

答案 0 :(得分:0)

意图服务将保存一个自动在单独线程上运行的意图队列。只要有要处理的消息,该服务就会存在。保证消息按顺序运行。

您无法控制服务何时完成其生命周期,但这对您来说无关紧要。从你的角度来看,这一切都是透明的。

编辑:你需要手动处理队列并公开一种方法,以便在需要时清除它。

我相信Handler.removeMessages方法可以解决问题。

另请看一下:Drop intents while IntentService is processing

编辑:

我自己从未这样做过,也无法确定它是否有效。你想要的是在发送之前设置消息的“内容”,以便你可以在之后将其删除。在onStart方法中,获取Message并设置两个参数。还可以尝试设置'what'参数。

答案 1 :(得分:0)

removeMessages不适合您的原因是因为what的{​​{1}}字段永远不会设置,您需要设置它然后相应地清除。