`
huakewoniu
  • 浏览: 46516 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics