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

Android實用技術(5)——Service進階技巧:前台服務與IntentService

編輯:關於 Android 開發

前面我們已經把Service的基礎用法摸清楚了,這一篇來看兩個實務上很常踩到的問題,以及對應的標準解法。

一、前台服務(Foreground Service)

問題:Service跑在背景,一旦系統記憶體吃緊,就可能把背景的Service回收掉。那要怎麼確保一個必須持續運行的服務不被系統殺掉?

解法:使用前台服務,呼叫 startForeground(),讓服務帶著一個常駐通知一起運行。

來看實際寫法:

public class MyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

        Intent intent = new Intent(getBaseContext(), MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        // 啟動服務後,在前台附加一個 Notification
        Notification no = new Notification.Builder(getBaseContext())
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker("Create a front desk Service!")
                .setContentTitle("This is a front desk service")
                .setContentText("A service skill!!!")
                .setContentIntent(pi)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .build();

        startForeground(1, no);
        Log.d(TAG, "onCreate executed");
    }
}

這段程式碼做的事,是在Service建立時掛上一個Notification,並呼叫 startForeground()。效果是:只要服務還活著,前景就會一直顯示這則通知。

補充兩個細節:如果在 onDestroy() 中呼叫 stopForeground(),通知會被移除,但Service本身仍然存在,此時它就又面臨被系統回收的風險;若直接停止Service,則通知與Service會一起銷毀。

二、IntentService

問題:Service的程式邏輯是跑在主執行緒上的。如果在裡面做耗時操作,很容易觸發ANR(應用無回應)。

直覺做法是開子執行緒,寫法如下:

public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 開啟一個子執行緒處理耗時操作
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
}

這樣服務啟動起來了,但若不呼叫 stopService() 或 stopSelf(),它就會一直運行。補上收尾:

new Thread(new Runnable() {
    @Override
    public void run() {
        // 處理具體邏輯
        stopSelf();   // 讓服務執行完邏輯後自行停止
    }
}).start();

這是標準的Service寫法,重點就兩個:建立子執行緒,以及呼叫 stopSelf()。實務上很容易漏掉其中一項,那有沒有更省事的作法?

解法:Android 內建了 IntentService(android.app.IntentService),一次解決這兩個需求。

(1)新增一個類別繼承 IntentService:

public class MyIntentService extends IntentService {

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

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("MyIntentService", "MyIntentServiceThread id is "
                + Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService", "onDestroy executed");
    }
}

這段程式碼做了三件事:

1、提供無參數建構子,並呼叫父類的有參數建構函式(THREAD_NAME 參數不可省略);

2、實作父類的抽象方法 onHandleIntent()。這個方法本身就是跑在子執行緒上的,因此服務呼叫它,邏輯就等同跑在子執行緒裡。一句話概括:onHandleIntent = Thread().start() + stopSelf();

3、onHandleIntent() 執行完畢後會自動銷毀服務,效果等同 stopSelf()。

(2)在版面配置中新增一個按鈕:

<Button
    android:id="@+id/start_intent_service"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/intent_service"/>

(3)修改 MainActivity:

public class MainActivity extends Activity {

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

        Button startIntentService = (Button) super.findViewById(R.id.start_intent_service);
        startIntentService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 查看主執行緒的 id
                Log.d("MyIntentService", "MainActivity Thread id is "
                        + Thread.currentThread().getId());

                Intent intentService = new Intent(getBaseContext(), MyIntentService.class);
                startService(intentService);
            }
        });
    }
}

(4)別忘了在 AndroidManifest 中註冊服務:

<service android:name=".MyIntentService" />

結果:

從Log可以看到兩件事:一、MyIntentService 與 MainActivity 所屬的執行緒 id 不同;二、onHandleIntent() 在邏輯執行完後確實銷毀了服務,效果等同 stopSelf()。這個方法真的很好用。

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