android intentService 学习

当启动一个Service时,他默认都是运行在主线程的,如果Service将要运行非常耗时或者可能被阻塞的操作时,应用程序将会被挂起,甚至会出现ANR错误。为了避免这一问题,应该在Service中重新启动一个新的线程来进行这些操作。但有一个更好的方法那就是用IntentService
      IntentService使用队列的方式将请求的Intent加入队列,然后开启一个工作线程来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,这里就给我们提供了一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作:

service.java:

[java]

package com.morgen.service;   

import android.app.Service;   

import android.content.Intent;   

import android.os.IBinder;   

public class MyService extends Service {   

  @Override   

    public void onCreate() {   

        super.onCreate();   

    }    

   @Override   

    public void onStart(Intent intent, int startId) {   

        super.onStart(intent, startId);   

        //Service里面是不能进行耗时的操作的,必须要手动开启一个工作线程来处理耗时操作   

        System.out.println("onStart");   

        try {   

            Thread.sleep(20000);   

        } catch (InterruptedException e) {   

            e.printStackTrace();   

        }   

        System.out.println("睡眠结束");   

    }   

   @Override   

    public IBinder onBind(Intent intent) {   

        return null;   

    }   

}   

Intentservice.java:

[java] 

package com.morgen.service;    

import android.app.IntentService;   

import android.content.Intent;   

   

public class MyIntentService extends IntentService {   

   

    public MyIntentService() {   

        super("m");   

    }   

    @Override   

    protected void onHandleIntent(Intent intent) {   

        // IntentService里面是可以进行耗时的操作的   

         

        System.out.println("onStart");   

        try {   

            Thread.sleep(20000);   

        } catch (InterruptedException e) {   

            e.printStackTrace();   

        }   

        System.out.println("睡眠结束");   

    }   

}   

入口代码:

[java]

package com.morgen.service;   

import android.app.Activity;   

import android.content.Intent;   

import android.os.Bundle;   

   

public class ServiceDemoActivity extends Activity {   

    @Override   

    public void onCreate(Bundle savedInstanceState) {   

        super.onCreate(savedInstanceState);   

        setContentView(R.layout.main);   

        startService(new Intent(this,MyService.class));//主界面阻塞,会出现Application not responding   

        //连续两次启动IntentService,会发现应用程序不会阻塞,第二次的请求会再第一个请求结束之后运行 

        startService(new Intent(this,MyIntentService.class));   

        startService(new Intent(this,MyIntentService.class));   

    }   

}   

来看看IntenService的源码(android 4.0):

[java] 

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

        } 

    } 

可以看出IntentService不仅有服务的功能,还有处理和循环消息的功能.

下面是onCreate()的源码:

[java] 

public void onCreate() { 

       super.onCreate(); 

       HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); 

       thread.start(); 

       mServiceLooper = thread.getLooper(); 

       mServiceHandler = new ServiceHandler(mServiceLooper); 

   } 

IntentService创建时就会创建Handler线程并且启动,然后再得到当前线程的Looper对象来初始化IntentService的ServiceLooper,接着创建Servicehandler对象.

下面是onStart()的源码:

[java] 

public void onStart(Intent intent, int startId) { 

       Message msg = mServiceHandler.obtainMessage(); 

       msg.arg1 = startId; 

       msg.obj = intent; 

       mServiceHandler.sendMessage(msg); 

   } 

当启动IntentService的时候,就会产生一条附带startId和Intent的Message并发送到MessageQueue中,接下来Looper发现MessageQueue中有Message的时候,就会停止Handler处理消息,接下来处理的代码如下:

[java]

public void handleMessage(Message msg) { 

          onHandleIntent((Intent)msg.obj); 

          stopSelf(msg.arg1); 

      } 

  } 

调用onHandleIntent((Intent)msg.obj),可以在这个方法里面处理我们的工作.当任务完成时就会调用stopSelf(msg.arg1)这个方法来结束指定的工作

当所有的工作执行完后:就会执行onDestroy方法:

[java] 

public void onDestroy() {  

                mServiceLooper.quit();  

        } 

从源码中我们可以看到,IntentService是一个基于消息的服务,每次启动该服务并不是马上处理你的工作,而是首先会创建对应的Looper和Handler并且在MessageQueue中添加的附带客户Intent的Message对象,当Looper发现有Message的时候接着得到Intent对象通过在onHandleIntent((Intent)msg.obj)中调用你的处理程序.处理完后即会停止自己的服务.接着处理MessageQueue的下一个Message对象。

转:http://www.2cto.com/kf/201302/191986.html

猜你喜欢

转载自zjingye.iteye.com/blog/1965758
今日推荐