編輯: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,訊息服務與執行緒都能乾淨地結束。這便是訊息推送機制背後的核心原理。
Android MediaPlayer 教學:打造可播放、暫停、快轉的音樂播放器
Android 提供了多種播放音訊與影片的方式,其中最直接、也最常被拿來播放應用程式內建媒體檔案的,就是 MediaPlayer 這個類別。它其實是內建媒體播放服務的一層
Android JSON 解析入門:用 JSONObject 取出你真正需要的那幾個欄位
JSON(JavaScript Object Notation)是一種不依附任何程式語言的純文字資料格式。它不像 XML 需要層層疊疊的標籤與屬性宣告,因此在行動網路上傳
Android仿QQ登錄界面實現原理與完整代碼
今天我們拿騰訊 QQ 練練手,一起做一個既簡潔又漂亮的登錄界面。先看官方效果圖:程序啟動後先進入啟動頁(SplashActivity),隨後跳轉到登錄頁。導航頁這裡就不展
Android手機衛士(十八):依密碼狀態切換對話框
本篇開始實作設定中心的「手機防盜」模塊。點擊手機防盜時,需要根據本地是否已經保存密碼,決定要顯示「首次設定密碼」或「輸入密碼確認」的對話框。若尚未設定密碼,會出現設定密碼