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

Android Service 全解析(三):IntentService 如何優雅避開 ANR

編輯:關於 Android 程式設計

很多人第一次在 Service 裡寫耗時任務,都會直接撞上 ANR(Application Not Responding)對話框。問題不在 Service 本身,而在於對它的理解偏差。本文用一組對照實驗說明 Service 與 IntentService 的差異。

先釐清兩個誤解

誤解一:Service 是獨立進程。事實上 Service 與它所在的應用位於同一個進程,只是生命週期由系統單獨管理。

誤解二:Service 是一條新線程。它也不是。Service 的所有回呼都跑在應用主線程上,因此在裡面呼叫 Thread.sleep() 這種長時間阻塞操作,等同於卡住 UI 執行緒,ANR 幾乎是必然結果。

IntentService 之所以能解決這個問題,是因為它繼承自 Service,但會在 onHandleIntent() 中開啟一條工作線程來處理任務,處理完畢後自動停止自己。

實驗一:兩顆按鈕

package cc.testservice3;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button mStartServiceButton;
    private Button mStartIntentServiceButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        // 利用 Service 執行耗時任務
        mStartServiceButton = (Button) findViewById(R.id.startServiceButton);
        mStartServiceButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(MainActivity.this, ServiceSubclass.class);
                startService(intent);
            }
        });

        // 利用 IntentService 執行耗時任務
        mStartIntentServiceButton = (Button) findViewById(R.id.startIntentServiceButton);
        mStartIntentServiceButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(MainActivity.this, IntentServiceSubclass.class);
                startService(intent);
            }
        });
    }
}

實驗二:普通 Service 會卡住主線程

package cc.testservice3;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class ServiceSubclass extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public void onCreate() {
        System.out.println("---> Service onCreate()");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        System.out.println("---> Service onStart()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("---> Service onStartCommand()");
        // 模擬耗時操作:這段會直接阻塞主線程
        try {
            Thread.sleep(30 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("---> Service onDestroy()");
    }
}

按下按鈕後,畫面會完全凍結三十秒,因為 onStartCommand() 正跑在主線程上。

實驗三:IntentService 自動開線程

package cc.testservice3;

import android.app.IntentService;
import android.content.Intent;

public class IntentServiceSubclass extends IntentService {

    public IntentServiceSubclass() {
        super("");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // 同樣的耗時操作,這裡跑在工作線程,不會造成 ANR
        try {
            Thread.sleep(30 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

這裡藏著一個經典陷阱:Eclipse 會提示你為 IntentService 的子類別生成一個帶 String 參數的建構子,若照著產生,執行時會直接拋出 java.lang.InstantiationException。原因是 IntentService 在工作階段需要透過無參數建構子被系統重建。

正確做法是刪除該提示產生的建構子,改寫一個無參數版本,並在其中呼叫 super("")。

佈局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <Button
        android:id="@+id/startServiceButton"
        android:layout_width="200dip"
        android:layout_height="150dip"
        android:text="啟動Service" />

    <Button
        android:id="@+id/startIntentServiceButton"
        android:layout_width="200dip"
        android:layout_height="150dip"
        android:text="啟動IntentService" />
</LinearLayout>

該用哪一個

IntentService 適合「任務序列化執行、做完就結束」的場景,例如上傳日誌、寫入快取、同步一筆資料。它會把收到的 Intent 排隊,逐一交給 onHandleIntent() 處理,全部完成後自動呼叫 stopSelf(),不需要手動管理生命週期。

但它也有明確限制:所有任務共用一條工作線程,無法併發;且一旦工作階段結束就無法再接收新任務。若需要多執行緒併發、需要長駐,或需要與使用者介面雙向溝通,就該改用 Service 搭配自己的執行緒或 ExecutorService,甚至考慮 JobScheduler、WorkManager 這類現代化解法。

另外要提醒的是,無論用哪一種,長時間背景工作在新版 Android 上都受到越來越嚴格的限制,前景服務通知與執行期權限已是必要配套。

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