Service的高级应用

下面是android Service的高级应用的一个例子,主要内容是在Service中spawn一个thread 来执行一写 CPU intensive的任务,以便让UI thread 能够更好的运行。

这里我们使用到了Looper 和 Handler 两个特殊的类。

Looper    是一个用来运行一个线程的Message循环 ,每一个线程都默认的有一个和他们相关联的Looper。

Handler 是Looper 用来处理这个线程的消息循环的类

 

整个流程的概括,调用Service的client 用Itent来调用这个Service,然后就会运行public void onStart(Intent intent, int startId), 我们通过Intent中不同的action 来确定client想要完成的工作。 根据不同的action给thread的消息队列发送不同的消息 

         Message msg = Message.obtain();
         msg.what = MSG_UPDATE;
         handler.sendMessage(msg);

下面是实现的详细代码

 public class MyService extends Service {

    private static final int MSG_UPDATE= 0;
    private static final int MSG_CANCLE = 1;
    /**
     * intent to update

     */
    public static final String ACTION_UPDATE =  "UPDATE";
   
    /**
     * intent to cancel     */
    public static final String ACTION_CANCLE = "CANCLE";
       
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler handler;
   
    private final class ServiceHandler extends Handler {
               
        public ServiceHandler(Looper looper) {
      super(looper);
    }

    @Override
        public void handleMessage(Message msg)
        {
         switch (msg.what) {
            case MSG_UPDATE:
     Log.v("TAG", "Update");               
                break;
            case MSG_CANCLE:
     Log.v("TAG", "Cancle");
             break;
        }
    };

 
    @Override
    public void onCreate() {
        super.onCreate();
        log.info("ReadingService.onCreate()");
       
        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.  We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
        HandlerThread thread = new HandlerThread("service",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
  //获取thread默认的Looper
        mServiceLooper = thread.getLooper();
        //用Looper来构造这个 Handler 这样的话 Looper就可以用这个Handler来处理thread的消息循环
        handler = new ServiceHandler(mServiceLooper);
    }

    // This is the old onStart method that will be called on the pre-2.0
    // platform.  On 2.0 or later we override onStartCommand() so this
    // method will not be called.
    @Override
    public void onStart(Intent intent, int startId) {
        handleCommand(intent);
    }

    //@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleCommand(intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return 1; // START_STICKY
    }

    private void handleCommand(Intent intent) {
     if (intent == null || (intent.getAction() == null)) {
      return;
     }
    
     String action = intent.getAction();
        if (ACTION_UPDATE.equals(action)) {
       //Return a new Message instance from the global pool
         Message msg = Message.obtain();
        //Message还可以携带信息
         msg.setData(intent.getExtras());
         msg.what = MSG_UPDATE;
         handler.sendMessage(msg);
        } else if (ACTION_CANCLE.equals(action)) {
        //从消息队列中删掉消息
         handler.removeMessages(MSG_UPDATE);
        }
    }

    @Override
    public void onDestroy() {
    //退出消息循环
      mServiceLooper.quit();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值