Android Service—繼承IntentService類

來源:互聯網
上載者:User

因為大多被啟動類型的服務不需要同時處理多個請求(這實際是一個危險的多線程情境),因此使用IntentService類來實現自己的服務可能是最好的。

IntentService類執行以下操作:

1.  建立一個獨立與應用程式主線程的預設背景工作執行緒,執行所有的給onStartCommand()方法Intent的處理;

2.  建立一個工作隊列,以便每次只給你的onHandleIntent()方法實現傳遞一個Intent,因此你不必擔心多線程的問題;

3.  所有的啟動請求都被處理之後終止這個服務,因此你不需要自己去調用stopSelf()方法;

4.  提供返回null的onBind()方法的預設實現;

5.  提供一個給工作隊列發送Intent對象的onStartCommand()方法的預設實現和onHandleIntent()方法的實現。

所以這些加起來實際上只需要實現onHandleIntent()方法,來完成由客戶提供的工作(雖然,你還需要給服務提供一個小的構造器)。

例如:

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) {
              }
          }
      }
  }
}

以上就是你做的全部:一個構造器和一個onHandleIntent()方法的實現。

如果你還決定要重寫其他的回調方法,如onCreate()、onStartCommand()、或onDestroy(),那麼就要確保調用父類的實現,以便IntentService對象能夠適當的處理背景工作執行緒的活動。

例如,onStartCommand()方法必須返回預設的實現(預設的實現擷取Intent並把它交付給onHandleIntent()方法):

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

除了onHandleIntent()方法以外,唯一不需要調用實現的方法是onBind()方法(但是如果你的服務允許綁定,就要實現這個方法)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.