Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 開發系列(七):App 訊息通知機制的完整實作

編輯:Android 開發實例

訊息推送幾乎是每一款 App 都會碰到的需求,本文把它的原理與實作要點整理成一份實用筆記,不求面面俱到,但求真正用得上。

一、訊息推送的基本概念

傳統的請求模式是被動的:客戶端去問,伺服器才回。而推送機制剛好相反,伺服器主動通知使用者重要的資訊,而且無論 App 正在執行或已關閉,都能收到通知。一句話概括就是:「Don't call me, I will call you!」想像 QQ 在右下角突然彈出一則對話框,就是最直觀的例子。這種設計帶來便利,但也考驗著分寸拿捏——自作聰明固然討喜,用過頭也會惹人厭。

二、用獨立行程確保隨時可通知

要做到不論 App 是否在前景都能收到通知,我們需要一個獨立於主介面的背景服務。在 AndroidManifest.xml 註冊 Service 時,可以透過 android:process 屬性來指定行程:

<!--以「.」開頭,會建立一個全域的 com.cnblogs.tianxia.message 獨立行程-->
<service android:name=".service.MessageService" android:label="消息推送" android:process=".message" />
<!--或者-->
<!--以「:」開頭,會建立一個此應用私有的 com.cnblogs.tianxia:message 獨立行程-->
<service android:name=".service.MessageService" android:label="消息推送" android:process=":message" />

本文選擇第二種寫法,建立屬於當前應用私有的獨立行程,避免不必要的全域資源佔用。

三、發出通知並處理點擊查看

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 int onStartCommand(Intent intent, int flags, int startId) {
  // 初始化
  messageNotification = new Notification();
  messageNotification.icon = R.drawable.icon;
  messageNotification.tickerText = "新消息";
  messageNotification.defaults = Notification.DEFAULT_SOUND;
  messageNotificatioManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  messageIntent = new Intent(this, MessageActivity.class);
  messagePendingIntent = PendingIntent.getActivity(this, 0, messageIntent, 0);
  // 開啟執行緒
  messageThread = new MessageThread();
  messageThread.isRunning = true;
  messageThread.start();
  return super.onStartCommand(intent, flags, startId);
 }

 /** 從伺服器端取得消息 */
 class MessageThread extends Thread {
  // 運行狀態,後續步驟會用到
  public boolean isRunning = true;
  public void run() {
   while (isRunning) {
    try {
     // 每 10 分鐘輪詢一次
     Thread.sleep(600000);
     String serverMessage = getServerMessage();
     if (serverMessage != null && !"".equals(serverMessage)) {
      // 更新通知欄
      messageNotification.setLatestEventInfo(MessageService.this, "新消息", "收到一則新訊息:" + serverMessage, messagePendingIntent);
      messageNotificatioManager.notify(messageNotificationID, messageNotification);
      // 每次通知後遞增 ID,避免訊息被覆蓋
      messageNotificationID++;
     }
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 }

 /** 此處以本方法模擬伺服器,僅作示範
  * @return 回傳要推送的訊息,若為空則不推送 */
 public String getServerMessage() {
  return "YES!";
 }
}

其中 MessageActivity 是點擊通知後跳轉的頁面,負責顯示詳細內容。在其他 Activity 中只要這樣呼叫即可啟動服務:

boolean isMessagePush = true; // 不開啟就設為 false
// ...
if (isMessagePush) {
 startService(new Intent(this, MessageService.class));
}

四、停止服務

stopService(new Intent(MyActivity.this, MessageService.class));
setMessagePush(false); // 於設定檔或資料庫中把 flag 設為 false

實測時會發現一個反常現象:服務明明停了,執行緒卻還在跑。原因不在程式碼寫錯,而是我們只停了服務,卻沒停下行程裡的執行緒。

五、正確退出執行緒

實踐證明,Thread 的 stop() 方法並不可靠,但我們仍有其他做法,以下提供兩種:

第一種:強制退出。

// 直接終結執行緒所在的行程,執行緒自然跟著結束
System.exit(0);

第二種:把 isRunning 設為 false。

// isRunning 設為 false 後,執行緒會跳出 while 迴圈並自然結束
messageThread.isRunning = false;

綜合兩種做法,我們在 MessageService 中重寫 onDestroy():

@Override
public void onDestroy() {
 System.exit(0); // 二選一,推薦此法,行程退出得更乾淨
 // messageThread.isRunning = false;
 super.onDestroy();
}

如此一來,不論是手動停止,還是從工作管理員強制結束 Service,訊息服務與執行緒都能乾淨地結束。這便是訊息推送機制背後的核心原理。

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