`

IntentService

阅读更多
看android的源码可以发现很多很多有趣有用的代码,今天在看关于NFC 的Tag源码的时候,发现了IntentService.做应用程序真的可以很快就完成,因为已经有了很多很多现成的API用,帮我们做了很多的事情。就拿IntentService来说:

Class Overview

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

IntentService是Service的子类,可以通过处理异步的请求(用Intent的方式)。Service可以在需要的时候启动,并且用单独的thread处理每个Intent,但处理完之后就会取消自己。

这种“工作队列的处理器”方式是普遍用于从应用程序的主线程分出来的任务。
所有的请求都会在一个单独的线程处理,但不会阻塞应用程序的主线程。并且一次只处理一个请求。

我们看Tag应用程序里面用IntentService的例子:

/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.apps.tag;

import com.android.apps.tag.provider.TagContract.NdefMessages;

import android.app.IntentService;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.os.Parcelable;
import android.util.Log;

public class TagService extends IntentService {
    private static final String TAG = "TagService";

    private static final String EXTRA_SAVE_MSGS = "msgs";
    private static final String EXTRA_DELETE_URI = "delete";
    private static final String EXTRA_STAR_URI = "set_star";
    private static final String EXTRA_UNSTAR_URI = "remove_star";
    private static final String EXTRA_STARRED = "starred";
    private static final String EXTRA_PENDING_INTENT = "pending";

    private static final boolean DEBUG = true;

    public TagService() {
        super("SaveTagService");
    }

    @Override
    public void onHandleIntent(Intent intent) {
        if (intent.hasExtra(EXTRA_SAVE_MSGS)) {
            Parcelable[] msgs = intent.getParcelableArrayExtra(EXTRA_SAVE_MSGS);
            NdefMessage msg = (NdefMessage) msgs[0];

            ContentValues values = NdefMessages.toValues(this, msg, false, System.currentTimeMillis());
            Uri uri = getContentResolver().insert(NdefMessages.CONTENT_URI, values);

            if (intent.hasExtra(EXTRA_PENDING_INTENT)) {
                Intent result = new Intent();
                result.setData(uri);

                PendingIntent pending = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_INTENT);

                try {
                    pending.send(this, 0, result);
                } catch (CanceledException e) {
                    if (DEBUG) Log.d(TAG, "Pending intent was canceled.");
                }
            }

            return;
        }

        if (intent.hasExtra(EXTRA_DELETE_URI)) {
            Uri uri = (Uri) intent.getParcelableExtra(EXTRA_DELETE_URI);
            getContentResolver().delete(uri, null, null);
            return;
        }

        if (intent.hasExtra(EXTRA_STAR_URI)) {
            Uri uri = (Uri) intent.getParcelableExtra(EXTRA_STAR_URI);
            ContentValues values = new ContentValues();
            values.put(NdefMessages.STARRED, 1);
            getContentResolver().update(uri, values, null, null);
        }

        if (intent.hasExtra(EXTRA_UNSTAR_URI)) {
            Uri uri = (Uri) intent.getParcelableExtra(EXTRA_UNSTAR_URI);
            ContentValues values = new ContentValues();
            values.put(NdefMessages.STARRED, 0);
            getContentResolver().update(uri, values, null, null);
        }
    }

    public static void saveMessages(Context context, NdefMessage[] msgs, boolean starred,
            PendingIntent pending) {
        Intent intent = new Intent(context, TagService.class);
        intent.putExtra(TagService.EXTRA_SAVE_MSGS, msgs);
        intent.putExtra(TagService.EXTRA_STARRED, starred);
        intent.putExtra(TagService.EXTRA_PENDING_INTENT, pending);
        context.startService(intent);
    }

    public static void delete(Context context, Uri uri) {
        Intent intent = new Intent(context, TagService.class);
        intent.putExtra(TagService.EXTRA_DELETE_URI, uri);
        context.startService(intent);
    }

    public static void setStar(Context context, Uri message, boolean star) {
        Intent intent = new Intent(context, TagService.class);
        if (star) {
            intent.putExtra(EXTRA_STAR_URI, message);
        } else {
            intent.putExtra(EXTRA_UNSTAR_URI, message);
        }
        context.startService(intent);
    }
}


如果我们不用IntentService,我们就自己得用AsyncTask,Looper, Handler来处理。其实若去看IntentService的源码就知道,IntentSerice已经帮我们做了这些事情。所以我们用起来就方便快捷了。^_^
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics