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

Android 自訂訊息推送:Service 結合 Notification 的實作示範

編輯:關於 Android 程式設計

先來看效果。

點擊通知之後的樣子:

主介面:控制服務的啟動與停止

public class TextActivity extends Activity {
    Button button;
    Button buttonstop;

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

        button = (Button) findViewById(R.id.button);
        buttonstop = (Button) findViewById(R.id.titlebutton);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setAction(com.text.ac.action.MY_SERVICE);
                startService(intent);
            }
        });

        buttonstop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setAction(com.text.ac.action.MY_SERVICE);
                stopService(intent);
            }
        });
    }
}

這裡用顯式 Intent 的 setAction 而非指定 class,屬於比較鬆散的耦合方式。實務上更推薦直接 new Intent(this, MessageService.class),行為明確也不容易被其他元件攔截。

服務本體:背景輪詢 + 通知欄更新

public class MessageService extends Service {
    private MessageThread messageThread = null;
    private Intent messageIntent = null;
    private PendingIntent messagePendingIntent = null;
    private int messageNotificationID = 1000;
    private Notification messageNotification = null;
    private NotificationManager messageNotificatioManager = null;

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

    @Override
    public void onCreate() {
        messageNotification = new Notification();
        messageNotification.icon = R.drawable.ic_hehe;
        messageNotification.tickerText = "新訊息";
        messageNotification.defaults = Notification.DEFAULT_SOUND;

        messageNotificatioManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);

        messageIntent = new Intent(this, TextActivity.class);
        messagePendingIntent = PendingIntent.getActivity(this, 0, messageIntent, 0);

        messageThread = new MessageThread();
        messageThread.isRunning = true;
        messageThread.start();

        Toast.makeText(MessageService.this, "aaaa", Toast.LENGTH_LONG).show();
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        messageThread.isRunning = false;
        super.onDestroy();
    }

    public String getServerMessage() {
        return "不錯哦";
    }
}

輪詢線程

class MessageThread extends Thread {
    public boolean isRunning = true;

    public void run() {
        while (isRunning) {
            try {
                Thread.sleep(5000);
                String serverMessage = getServerMessage();
                if (serverMessage != null and !"".equals(serverMessage)) {
                    messageNotification.setLatestEventInfo(
                        MessageService.this,
                        "新訊息",
                        "您中獎了,500萬!" + serverMessage,
                        messagePendingIntent);
                    messageNotificatioManager.notify(
                        messageNotificationID, messageNotification);
                    messageNotificationID++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

兩個設計細節值得說明。第一,通知 ID 每次遞增,目的是避免新訊息覆蓋舊訊息——若固定使用同一個 ID,後到的通知會直接把前面的頂掉。第二,onDestroy 中把 isRunning 設為 false 讓迴圈退出,這是讓線程優雅結束的必要步驟;若不這麼做,Service 銷毀了但線程還在跑,就會造成洩漏。

這份示範程式碼的幾個問題

它適合理解原理,但直接搬到專案裡會遇到麻煩,這裡誠實列出來:

1. setLatestEventInfo 與直接 new Notification() 這套寫法在 API 26 之後已不適用。新版本必須使用 NotificationCompat.Builder 搭配 NotificationChannel,否則通知根本不會顯示。

2. 後台 Service 在 Android 8.0 之後受限嚴格,長時間運行需要改為前景服務(startForeground)並顯示常駐通知,或使用 WorkManager 這類由系統調度的方案。

3. 用 Thread.sleep 做輪詢既耗電又不可靠,實際的推送應該由服務端主動下發,客戶端透過長連線(WebSocket、MQTT)或各家廠商的推送服務接收。

4. PendingIntent.getActivity 在 Android 12 之後必須顯式聲明 FLAG_IMMUTABLE 或 FLAG_MUTABLE,否則會拋出例外。

5. super.onCreate() 應該放在方法開頭而非結尾,這是 Android 生命週期方法的通用約定。

理解「Service 跑背景邏輯、NotificationManager 負責呈現、PendingIntent 處理點擊跳轉」這三者的分工,是這份程式碼真正的價值所在;具體 API 則建議對照當前版本的官方文件重寫。

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