一:用法

public class MyIntentService extends IntentService {    /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */    public MyIntentService() {        super("ServiceName");    }    /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */    @Override    protected void onHandleIntent(Intent intent) {        //在这里进行耗时操作,,和Service一样    }}

调用的时候:

   // 可以调用多次startService();   Intent intent=new Intent(this,MyIntentService.class);   startService(intent);   startService(intent);   startService(intent);

当然别忘了在AndroidManifest.xml里面进行注册。

二:用处

IntentService is a base class for {@link Service}s that handle asynchronous requests (expressed as {@link Intent}s) on demand. Clients send requests through {@link android.content.Context#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.(IntentService是Service的子类,用来处理异步请求,客户端可以通startService(Intent)方法传递请求给IntentService,IntentService处理每个Intent通过一个工作线程,执行完所一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,则自动停止Service;否则执行下一个Intent请求所对应的任务。)

IntentService做了以下几件事:

  • Creates a default worker thread that executes all intents delivered to onStartCommand()separate from your application’s main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
  • Stops the service after all start requests have been handled, so you never have to call stopSelf().
  • Provides default implementation of onBind() that returns null.
  • Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

三:HandlerThread

先说一下HandlerThread,因为IntentService将要使用这个类。

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

HandlerThreadThread的子类。
1构造方法:

//线程的名字public HandlerThread(String name) {        super(name);        mPriority = Process.THREAD_PRIORITY_DEFAULT;    } @Override    public void run() {        mTid = Process.myTid();        Looper.prepare();        synchronized (this) {            mLooper = Looper.myLooper();            notifyAll(); //唤醒所有的等待线程        }        Process.setThreadPriority(mPriority);        onLooperPrepared();        Looper.loop();//默认是死循环        mTid = -1;    }public Looper getLooper() {        if (!isAlive()) {            return null;        }        // If the thread has been started, wait until the looper has been created.        synchronized (this) {            while (isAlive() && mLooper == null) {                try {                    wait(); //如果 isAlive() 和 mLooper没有准备好就让当前线程进行等待                } catch (InterruptedException e) {                }            }        }        return mLooper;    }

这些还是比较好理解的,不理解的话说明对Hanlder Looper机制不是很理解,可以看这里。

HandlerThread,使用方法:

//参数为Thread的名字        HandlerThread handlerThread = new HandlerThread("WQH");        handlerThread.start(); //必须调用 在run()方法里面创建了一个LooperThread 来处理消息        // superHandler的创建需要一个Looper 将HandlerThread的Looper对象传递给superHandler 使superHandler在其他线程中进行消息处理        // superHandler发送的Message将在HandlerThread中进行处理        Handler superHandler = new Handler(handlerThread.getLooper()) {            @Override            public void handleMessage(Message msg) {                // TODO Auto-generated method stub                super.handleMessage(msg);                Log.d(TAG, Thread.currentThread().getName() + " HandlerThread is OK");            }        };        superHandler.sendEmptyMessage(1);

四:IntentService代码研读

    //感觉没什么好说的    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);         }    }    //构造方法 线程名字    public IntentService(String name) {        super();        mName = name;    }    //Service 的onCreate()方法,    @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发送的消息将送至 thread进行处理        mServiceHandler = new ServiceHandler(mServiceLooper);    }@Override    public void onStart(Intent intent, int startId) {        Message msg = mServiceHandler.obtainMessage();        msg.arg1 = startId;  //ServiceHandler 中通过msg.arg1来stopSelf(msg.arg1);        msg.obj = intent;        mServiceHandler.sendMessage(msg);    } @Override    public IBinder onBind(Intent intent) {        return null;    }//在工作线程下被调用//@param intent The value passed to {@link android.content.Context#startService(Intent)}. @WorkerThread    protected abstract void onHandleIntent(Intent intent);

所以在使用IntentService只需要复写构造函数和onHandleIntent就OK了。最后调用的时候,IntentService将所用的Intent放在一个Work Thread下进行处理。

更多相关文章

  1. 破解android签名验证
  2. Service启动之启动方式和绑定方式
  3. android的事件分发
  4. Android图形绘制基础(一)
  5. Android(安卓)调用H5界面(交互)
  6. InputFilter方法filter 解释
  7. APK应用LOG保存
  8. Android工程方法数超过65535,解决办法
  9. Android屏幕旋转和Configuration的使用

随机推荐

  1. android 本地化[ICU4J Android 框架 API]
  2. Android(安卓)Crash 报告反馈
  3. 初学Android,"Hello World" 第一个Androi
  4. android小白
  5. Android(安卓)调用相机以及调用系统图片
  6. android studio 开发遇到的相关问题
  7. Android性能优化(十一)之正确的异步姿势
  8. android 笔记 --- 按钮上面的文字滚动起
  9. Android中资源管理机制详解
  10. android 如何用代码生成圆角Bitmap图片