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

用獨立進程的 Service 模擬離線推送(Server Push)

編輯:關於 Android 程式設計

要解決的問題

以 QQ 為例:使用者已經退出 App、甚至 App 不在最近任務清單裡,好友送來的訊息卻仍然能收到並跳通知。要做到這件事,需要一個在介面關閉後仍持續運作、並且與主程式互不影響的常駐元件。

關鍵:android:process 屬性

在 AndroidManifest 註冊 Service 時,android:process 決定它跑在哪個進程:

  • 不寫這個屬性:Service 與應用共用工匠同一個進程與主執行緒。
  • 以「:」開頭(例如 :message):為此 Service 建立一個「本應用私有」的獨立進程。
  • 以完整套件名稱開頭:與另一個同簽名的應用共用進程,可用於多 App 共享記憶體。

獨立進程的好處是記憶體與生命週期與 UI 脫鉤,主程式被回收時它仍可能存活;代價是進程間溝通要走 Binder、AIDL 或 Messenger,資料不能靠靜態變數傳遞。

Service 實作

package com.example.serverpush;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class ServerPushService extends Service {

    private NotificationManager mNotificationManager;
    private int mNotificationId = 1000;

    @Override
    public IBinder onBind(Intent intent) {
        return null;   // 不需要綁定式服務
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        MessageThread thread = new MessageThread();
        thread.setRunning(true);
        thread.start();
        // START_STICKY:被系統回收後盡量重建
        return START_STICKY;
    }

    /** 定時向伺服器確認是否有新訊息 */
    class MessageThread extends Thread {
        private volatile boolean mRunning = false;

        void setRunning(boolean running) {
            mRunning = running;
        }

        @Override
        public void run() {
            while (mRunning) {
                try {
                    Thread.sleep(10000);   // 實務上應改用 AlarmManager 或長連線
                    if (!"yes".equals(fetchServerMessage())) {
                        continue;
                    }
                    notifyUser();
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    }

    private void notifyUser() {
        Intent intent = new Intent(this, MessageActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, mNotificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("您有新訊息")
                .setContentText("這是一條新的測試訊息")
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();

        mNotificationManager.notify(mNotificationId++, notification);
    }

    /** 模擬向伺服器取訊息,實作時替換為真正的網路請求 */
    private String fetchServerMessage() {
        return "yes";
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

原文使用的 setLatestEventInfo() 早已被移除,Android 4.1 之後必須改用 Notification.Builder(新版為 NotificationCompat.Builder),並在 Android 8.0 以上建立 NotificationChannel,否則通知完全不會顯示。另外,通知 ID 採用自增可避免新訊息互相覆蓋,這點原做法仍然值得沿用。

註冊到獨立進程

<!-- 為此應用建立私有獨立進程 -->
<service
    android:name=".ServerPushService"
    android:process=":message"
    android:exported="false" />

啟動服務

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(this, ServerPushService.class));
}

進入頁面即啟動服務,之後即使關閉介面,:message 進程仍會持續輪詢伺服器並發出通知,這就是「離線推送」的模擬效果。

為什麼它只是「模擬」

用常駐進程輪詢的寫法在教學上很好懂,但放在真實產品裡問題不少:Android 8.0 起後台服務受限,Android 9 之後更要求改用 startForegroundService 並顯示常駐通知;Doze 模式與 App Standby 會讓定時任務被大幅延後;各家 ROM 也會主動清理常駐進程。因此正式環境的離線推送應交由 FCM、JPush 這類長連線推送服務,應用端只負責接收與呈現,既省電又穩定。理解輪詢原理有助於除錯,但別把它當成最終方案。

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