在一个服务使用活套是与使用一个单独的线程? [英] using a Looper in a Service is the same as using a separate thread?

查看:219
本文介绍了在一个服务使用活套是与使用一个单独的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从文档这个例子( https://developer.android.com /guide/components/services.html#ExtendingService ),我们使用一个线程的尺蠖,我们用它在服务类,然后该服务将工作,如果它是在一个单独的线程?

In this example from the documentation (https://developer.android.com/guide/components/services.html#ExtendingService), we use the "looper" of a thread, and we use it in the Service class, and then the Service will be working as if it was in a separate thread?

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

感谢

推荐答案

线程(A HandlerThread )在的onCreate ,当你调用 thread.start(); ,那么你得到的到的尺蠖参考线程创建一个处理程序尺蠖 HandlerThread 创建) $ C>和处理程序用来发布消息的线程。在尺蠖是等待在,而(真)循环消息的对象。

The thread (a HandlerThread) is started in onCreate, when you call thread.start();, then you get a reference to the Looper of that thread (only one Looper is created per HandlerThread) to create a Handler and the Handler is used to post messages to the thread. The Looper is the object that waits for the messages in a while(true) loop.

每次有命令发送到服务服务发布消息到 HandlerThread 通过处理程序

Every time a command is sent to the Service, the Service posts a message to the HandlerThread through the Handler.

在源$ C ​​$ C仔细看会帮助你更好地理解它是如何工作的。有一个关于处理程序尺蠖■在的广场工程博客 - 在Android主线程之旅 - 第1部分

A closer look at the source code will help you understand better how it all works. There's an excelente post about Handlers and Loopers at Square Engineering Blog - A journey on the Android Main Thread - Part 1.

您也可以使用 IntentService 以避免初始化你自己的线程

You can also use an IntentService to avoid instantiating your own threads.

这篇关于在一个服务使用活套是与使用一个单独的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆