Service和IntentService

来源:互联网 发布:网络展示平台 编辑:程序博客网 时间:2024/06/07 05:36

关于普通service有两个点要注意:

  1. Service不是一个单独的进程 ,它和应用程序在同一个进程中

  2. Service不是一个线程,所以我们应该避免在Service里面进行耗时的操作

IntentService会构造一个工作线程,并在工作线程中执行onHandleIntent方法,在执行完毕后结束service。


IntentService官方文档中的用法

public class HelloIntentService extends IntentService {  /**   * A constructor is required, and must call the super IntentService(String)   * constructor with a name for the worker thread.   */  public HelloIntentService() {    super("HelloIntentService");  }  /**   * The IntentService calls this method from the default worker thread with   * the intent that started the service. When this method returns, IntentService   * stops the service, as appropriate.   */  @Override  protected void onHandleIntent(Intent intent) {    // 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) {        }      }    }  }}
0 0
原创粉丝点击