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

Android 頂欄定時推送訊息的實作與實現方案比較

編輯:關於 Android 程式設計

使用 Android 裝置時,通知欄推送幾乎無所不在。下面把自己寫過的一份定時推送程式碼整理出來供大家參考,也歡迎提出不同思路一起交流。

搜尋這個主題的朋友不少。這裡示範的是純本機的定時推送;若需要與伺服器即時聯動,則得靠雲推 SDK 才能滿足需求,文末一併說明。

第一步:在 manifest 註冊元件

 <!-- 安卓推送服務 --> <service android:name=".MessageService" android:enabled="true" android:exported="true" android:label="PushService" android:launchMode="singleInstance" android:persistent="true" android:process=":push" > <intent-filter> <action android:name="com.xxxx.action.MY_SERVICE" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </service> <receiver android:name="com.tt.xxxxx.download.GTAlarmReceiver" android:permission="com.android.launcher.permission.INSTALL_SHORTCUT" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="com.android.launcher.action.INSTALL_SHORTCUT" /> </intent-filter> </receiver> <!--end add-->

這段配置裡的 android:process=":push" 與 persistent 等屬性影響甚大,不清楚的話建議先查一下各欄位的官方說明再動手。

第二步:撰寫推送服務

 /******************************** 類 *************************************/ package com.ttad.yxcb; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; import java.text.SimpleDateFormat; import com.tt.yingxiongchibis.download.GTDownloaderActivity; 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.app_icon_ucs; messageNotification.tickerText = "通知"; messageNotification.defaults = Notification.DEFAULT_SOUND; messageNotificatioManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); //點擊跳轉的activity messageIntent = new Intent(this, GTDownloaderActivity.class); messagePendingIntent = PendingIntent.getActivity(this,0,messageIntent,0); //開啟線程 messageThread = new MessageThread(); messageThread.isRunning = true; messageThread.start(); //Toast.makeText(MessageService.this, "", Toast.LENGTH_LONG).show(); super.onCreate(); } /** * 從服務器端獲取消息 * */ class MessageThread extends Thread{ //運行狀態,下一步驟有大用 public boolean isRunning = true; public void run() { while(isRunning){ try { //休息10分鐘 Thread.sleep(1000); //獲取服務器消息 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(); } } } } @Override public void onDestroy() { // System.exit(0); //或者,二選一,推薦使用System.exit(0),這樣進程退出的更干淨 messageThread.isRunning = false; //super.onDestroy(); } /** * 這裡以此方法為服務器Demo,僅作示例 * @return 返回服務器要推送的消息,否則如果為空的話,不推送 */ public String getServerMessage(){ SimpleDateFormat sdf=new SimpleDateFormat("HHmmss"); String date=sdf.format(new java.util.Date()); String in = date; if(date.equals("195500")) { String str = "定時任務時間到了,請按時處理,謝謝配合。"; return str; } else if(date.equals("212500")) { String str = "定時任務時間到了,請按時處理,謝謝配合。"; return str; } else { return ""; } } }

兩個細節值得注意:messageNotificationID++ 讓每則通知各自獨立,避免新訊息直接覆蓋舊的;而 setLatestEventInfo() 與舊版 Notification 寫法在新系統上已被淘汰,實際專案請改用 Notification.Builder 或 NotificationCompat。

第三步:啟動服務

 //推送 Intent intent = new Intent(); // 設置Action屬性 intent.setAction("com.ttad.yxcb.action.MY_SERVICE"); // 啟動該Service startService(intent); // startService(new Intent(ExTextActivity.this, MessageService.class));

Android 訊息推送方案補充

所謂推送,就是伺服器主動向行動裝置建立通道並傳送資訊。新聞客戶端每隔一段時間收到通知、微信與 GTalk 這類 IM 的即時提醒,背後都是同一套邏輯。常見實作有三條路:

簡訊(SMS):攔截並解析 SMS 內容以理解伺服器意圖,能做到完全即時,但成本高且高度依賴電信業者。

輪詢:由客戶端定時拜訪伺服器介面拉取新訊息。實作最簡單,但頻率太慢會延遲,太快則大量消耗網路與電力。

持久連線:效能表現最好,卻仍會耗電。需要一個常駐服務維持與伺服器的長連線(iOS 與 Google C2DM 都屬此類)。問題在於 Android 資源吃緊時系統會強制回收服務,連線隨之中斷。Apple 之所以穩定,是因為每台裝置只與單一伺服器保持一條連線,所有推送都經由該代理伺服器中轉,C2DM 也是同樣思路。

三者相較,持久連線仍最可行:把連線做成系統服務或開機啟動;或在 onDestroy() 中重新啟動服務,變相維持長連線。C2DM 內建於 Android 2.2,無法向下相容 1.6–2.1,且依賴 Google 伺服器,在國內網路環境下常常不可用。

XMPP 協議

XMPP 全稱 Extensible Messaging and Presence Protocol,前身是 Jabber 專案,是一套以 XML 為基礎的開放即時通訊協議,因 Google Talk 與網易泡泡而被廣泛認識。它的特色在於分散式架構與 XML 串流,且已完成 IETF 標準化。基於 TCP 之上運作,除了能提供長連線與伺服器/客戶端雙工通信,也不受系統版本與 Google 服務的限制,因此是相對理想的方案。

androidpn(Android Push Notification)是 XMPP 的 Java 開源實作,含完整客戶端與伺服器端,伺服器部分基於 openfire 修改而來,Web 層則採用 Spring 框架。客戶端使用 asmack(源自 openfire 生態的 smack 專案),直接引用其中的 asmack.jar 即可,透過 XMPPConnection 建立長連線並完成註冊、認證與通知接收。

伺服器端同樣以 Java 實作,包含兩個部分:監聽 5222 埠的 XMPP 服務,負責與客戶端通訊、身份認證與推送通知;以及一個輕量 HTTP 伺服器,負責接收 Web 請求。這種雙通道設計頗具巧思——萬一 TCP 埠被防火牆封鎖,仍可退回輪詢方式存取,穿透性因此更好。

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