android – 在服务中使用Looper与使用单独的线程相同?

在文档(https://developer.android.com/guide/components/services.html#ExtendingService)的这个例子中,我们使用了一个线程的“looper”,我们在Service类中使用它,然后Service就像在一个单独的线程中一样工作?

public class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {
          // Normally we would do some work here, like download a file.
          // For our sample, we just sleep for 5 seconds.
          long endTime = System.currentTimeMillis() + 5*1000;
          while (System.currentTimeMillis() < endTime) {
              synchronized (this) {
                  try {
                      wait(endTime - System.currentTimeMillis());
                  } catch (Exception e) {
                  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
          stopSelf(msg.arg1);
      }
  }

  @Override
  public void 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("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler 
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the
      // start ID so we know which request we're stopping when we finish the job
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);

      // If we get killed, after returning from here, restart
      return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
      // We don't provide binding, so return null
      return null;
  }

  @Override
  public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
  }
}

谢谢

解决方法:

线程(HandlerThread)在onCreate中启动,当你调用thread.start();然后你得到对该线程的Looper的引用(每个HandlerThread只创建一个Looper)来创建一个Handler并使用Handler将消息发布到线程. Looper是在while(true)循环中等待消息的对象.

每次向服务发送命令时,服务都会通过处理程序向HandlerThread发送消息.

仔细查看源代码将有助于您更好地了解它的工作原理.在Square Engineering Blog – A journey on the Android Main Thread – Part 1有一篇关于Handlers and Loopers的优秀帖子.

您还可以使用IntentService来避免实例化自己的线程.

上一篇:IntentService与HandlerThread的工作原理(个人笔记)


下一篇:Android Handler 机制(一):Handler 运行机制完整梳理