Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 後台訊息傳送:使用 IntentService 的實作思路

編輯:關於 Android 開發

Android 後台訊息傳送:使用 IntentService 的實作思路

在即時聊天或背景任務中,若使用者離開頁面導致 Activity 或 Fragment 被銷毀,正在傳送的訊息可能被中斷。此時可考慮使用 IntentService 處理非同步任務。

IntentService 概念

IntentService 是一個以工作執行緒處理 Intent 的 Service。它會依序處理每個請求,並在沒有工作時自行停止,因此適合背景上傳、訊息傳送等場景。

建立自定義 IntentService

public class UpLoadImgService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
        if (MainActivity.UPLOAD_IMG.equals(intent.getAction())) {
            uploadImg(intent.getStringExtra(MainActivity.EXTRA_IMG_PATH));
        }
    }
}

通知 UI 更新

背景任務完成後,若需要更新介面,可透過廣播通知 Activity 或 Fragment。

sendBroadcast(intent);

IntentService 的優點是生命週期由 Service 管理,不必自行建立複雜執行緒池,也能避免背景任務因頁面銷毀而立即中斷。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved