本文示範的推送方案基於 IBM 提供的 MQTT 協議實現,需要先把 wmqtt.jar 導入工程。整體結構很清晰:一個 PushService 常駐後台保持與 broker 的連接,內部類 MQTTConnection 實現 MqttSimpleCallback 接口並重寫 publishArrived,收到推送數據後彈出一個 Notification,點擊它便跳轉到指定 Activity。若需要更完整的背景,可先參考 Android 推送通知指南:https://www.linuxidc.com/Linux/2011-10/45373.htm。
package com.ata.push;
public class PushService extends Service {
public static final String TAG = "PushService";
private static final String MQTT_HOST = "172.16.26.41"; // 改成服務器 IP
private static final int MQTT_BROKER_PORT_NUM = 1883; // 改成服務器 port
private static MqttPersistence MQTT_PERSISTENCE = null; // 不使用持久化
private static boolean MQTT_CLEAN_START = true; // 每次都是全新連接
private static short MQTT_KEEP_ALIVE = 60 * 15;
// QoS 設為 0(最多一次),避免通知重復送達;代價是消息可能丟失
private static int[] MQTT_QUALITIES_OF_SERVICE = { 0 };
private static int MQTT_QUALITY_OF_SERVICE = 0;
private static boolean MQTT_RETAINED_PUBLISH = false; // broker 不保留消息
// 客戶端 ID,同時用作 topic 前綴,可支撐多個 App 共用一個 broker
public static String MQTT_CLIENT_ID = "ata";
private static final String ACTION_START = MQTT_CLIENT_ID + ".START";
private static final String ACTION_STOP = MQTT_CLIENT_ID + ".STOP";
private static final String ACTION_KEEPALIVE = MQTT_CLIENT_ID + ".KEEP_ALIVE";
private static final String ACTION_RECONNECT = MQTT_CLIENT_ID + ".RECONNECT";
private ConnectivityManager mConnMan; // 判斷網絡是否可用
private NotificationManager mNotifMan; // 展示收到的推送
private boolean mStarted;
private MQTTConnection mConnection;
private static final long KEEP_ALIVE_INTERVAL = 1000 * 60 * 28; // 應用層保活
private static final long INITIAL_RETRY_INTERVAL = 1000 * 10; // 重連初始間隔
private static final long MAXIMUM_RETRY_INTERVAL = 1000 * 60 * 30; // 重連上限
private SharedPreferences mPrefs;
public static final String PREF_STARTED = "isStarted";
public static final String PREF_DEVICE_ID = "deviceID";
public static final String PREF_RETRY = "retryInterval";
public static String NOTIF_TITLE = "ata";
private static final int NOTIF_CONNECTED = 0;
}
三個靜態方法封裝了 Intent 的構造,業務代碼只需一行調用即可控制服務:
// 在需要的地方直接調用該方法就啟動監聽了
public static void actionStart(Context ctx) {
Intent i = new Intent(ctx, PushService.class);
i.setAction(ACTION_START);
ctx.startService(i);
}
public static void actionStop(Context ctx) {
Intent i = new Intent(ctx, PushService.class);
i.setAction(ACTION_STOP);
ctx.startService(i);
}
public static void actionPing(Context ctx) { // 發送保活
Intent i = new Intent(ctx, PushService.class);
i.setAction(ACTION_KEEPALIVE);
ctx.startService(i);
}
onCreate 中取出 SharedPreferences、ConnectivityManager 與 NotificationManager,並調用 handleCrashedService():進程若曾被系統回收,會依據持久化的啟動標志做一次乾淨的重新啟動。onStart 則按 action 分派到 stop / start / keepAlive / reconnectIfNecessary。
@Override
public void onCreate() {
super.onCreate();
log("Creating service");
mStartTime = System.currentTimeMillis();
mPrefs = getSharedPreferences(TAG, MODE_PRIVATE);
mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
mNotifMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
handleCrashedService(); // 進程被回收後恢復狀態
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if (intent.getAction().equals(ACTION_STOP)) {
stop();
stopSelf();
} else if (intent.getAction().equals(ACTION_START)) {
start();
} else if (intent.getAction().equals(ACTION_KEEPALIVE)) {
keepAlive();
} else if (intent.getAction().equals(ACTION_RECONNECT)) {
if (isNetworkAvailable()) reconnectIfNecessary();
}
}
private synchronized void start() {
if (mStarted) { // 已在運行則直接返回,避免重復啟動
Log.w(TAG, "Attempt to start connection that is already active");
return;
}
connect();
registerReceiver(mConnectivityChanged,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private synchronized void stop() {
if (!mStarted) return;
setStarted(false);
unregisterReceiver(mConnectivityChanged);
cancelReconnect();
if (mConnection != null) {
mConnection.disconnect();
mConnection = null;
}
}
設備號是定位手機的唯一依據,connect() 從 SharedPreferences 取出它,取不到就放棄建連;建連失敗則交給 scheduleReconnect 做退避重試——重連間隔會按 4 倍遞增並且不超過 30 分鐘上限,一旦距上次啟動已足夠久則重置回 10 秒。
private synchronized void connect() {
String deviceID = mPrefs.getString(PREF_DEVICE_ID, null);
if (deviceID == null) {
log("Device ID not found.");
} else {
try {
mConnection = new MQTTConnection(MQTT_HOST, deviceID);
} catch (MqttException e) {
log("MqttException: " + (e.getMessage() != null ? e.getMessage() : "NULL"));
if (isNetworkAvailable()) scheduleReconnect(mStartTime);
}
setStarted(true);
}
}
// 用 AlarmManager 週期性喚醒,即使設備休眠也能維持連接
private void startKeepAlives() {
Intent i = new Intent();
i.setClass(this, PushService.class);
i.setAction(ACTION_KEEPALIVE);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + KEEP_ALIVE_INTERVAL,
KEEP_ALIVE_INTERVAL, pi);
}
public void scheduleReconnect(long startTime) {
long interval = mPrefs.getLong(PREF_RETRY, INITIAL_RETRY_INTERVAL);
long now = System.currentTimeMillis();
long elapsed = now - startTime;
if (elapsed < interval)
interval = Math.min(interval * 4, MAXIMUM_RETRY_INTERVAL);
else
interval = INITIAL_RETRY_INTERVAL;
mPrefs.edit().putLong(PREF_RETRY, interval).commit();
Intent i = new Intent();
i.setClass(this, PushService.class);
i.setAction(ACTION_RECONNECT);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmMgr.set(AlarmManager.RTC_WAKEUP, now + interval, pi);
}
網絡變化由 mConnectivityChanged 這個 BroadcastReceiver 監聽:有網就嘗試重連,斷網則主動銷毀 MQTT 連接並取消重連計時器,避免做無效嘗試。
publishArrived 是整個方案的落點:把 byte 數組轉成字符串,解析 JSON 取出 alert 與 id,再組裝 Notification。這裡設置了 FLAG_AUTO_CANCEL(點擊後自動消失)與 DEFAULT_ALL(默認鈴聲、震動、燈光),並用 PendingIntent 把 id 帶給目標 Activity。
public void publishArrived(String topicName, byte[] payload, int qos, boolean retained) {
String s = new String(payload); // 在這裡處理服務器推送過來的數據
showNotification(s);
}
private void showNotification(String content) {
Notification n = new Notification();
n.flags |= Notification.FLAG_SHOW_LIGHTS;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.defaults = Notification.DEFAULT_ALL;
n.icon = R.drawable.ic_dialog_info;
n.when = System.currentTimeMillis();
Log.i("PushService", "json===" + content);
String alert = null;
String id = null;
try {
JSONObject json = new JSONObject(content);
alert = json.optString("alert");
id = json.optString("id");
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, NewMesageInfoActivity.class);
intent.putExtra("url", "https://testing.portal.ataudc.com/message/" + id);
intent.putExtra("message_id", id);
intent.putExtra("id", id);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
n.setLatestEventInfo(this, NOTIF_TITLE, alert, pi); // 通知標題與內容
mNotifMan.notify(NOTIF_CONNECTED, n);
}
private class MQTTConnection implements MqttSimpleCallback {
IMqttClient mqttClient = null;
public MQTTConnection(String brokerHostName, String initTopic) throws MqttException {
String mqttConnSpec = "tcp://" + brokerHostName + "@" + MQTT_BROKER_PORT_NUM;
mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);
String clientID = MQTT_CLIENT_ID + "/" + mPrefs.getString(PREF_DEVICE_ID, "");
mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
mqttClient.registerSimpleHandler(this); // 注冊消息回調
initTopic = MQTT_CLIENT_ID + "/" + initTopic;
subscribeToTopic(initTopic); // 訂閱初始 topic
mStartTime = System.currentTimeMillis();
startKeepAlives();
}
public void disconnect() {
try {
stopKeepAlives();
mqttClient.disconnect();
} catch (MqttPersistenceException e) {
log("MqttException" + (e.getMessage() != null ? e.getMessage() : " NULL"), e);
}
}
private void subscribeToTopic(String topicName) throws MqttException {
if ((mqttClient == null) || (mqttClient.isConnected() == false)) {
log("Connection error" + "No connection");
} else {
String[] topics = { topicName };
mqttClient.subscribe(topics, MQTT_QUALITIES_OF_SERVICE);
}
}
public void connectionLost() throws Exception {
log("Loss of connection" + "connection downed");
stopKeepAlives();
mConnection = null;
if (isNetworkAvailable() == true) reconnectIfNecessary();
}
public void sendKeepAlive() throws MqttException {
publishToTopic(MQTT_CLIENT_ID + "/keepalive",
mPrefs.getString(PREF_DEVICE_ID, ""));
}
}
PushService 依靠設備號精準定位手機,而它是從 SharedPreferences 讀取的,所以必須事先寫入。把下面這段放在合適的 Activity 中即可:
// 啟動 PUSH 服務
mDeviceID = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE).edit();
editor.putString(PushService.PREF_DEVICE_ID, mDeviceID);
editor.commit();
Log.i("tag", "mDeviceID=====" + mDeviceID);
PushService.actionStart(getApplicationContext());
服務器端我用 PHP 實現,具體做法同樣可參考上面的推送通知指南。
這套代碼寫於早期 Android 版本,直接搬到新系統上會遇到幾處障礙:setLatestEventInfo 已廢棄,通知需改用 NotificationCompat.Builder 配合 NotificationChannel;後台常駐服務在較新版本中受限,需要前台服務(foreground service)並向用戶展示持續通知;AlarmManager 的精確重複鬧鐘也不再隨意放行。此外 MQTT_CLIENT_ID 若固定不變,多設備共用 broker 時 topic 前綴仍靠 deviceID 區分,這點設計是合理的;但 QoS 0 意味着消息可能丟失,對可靠性有要求時應升到 1 並配合持久化會話。