要在 Android 上做到「開機就自動跑起來,並持續接收伺服器推送」,需要三個部分配合:廣播接收器捕捉開機完成事件、常駐服務負責連線、以及背景執行緒實際跑收訊迴圈。以下依序實作。
<!-- 抓取系統啟動事件 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
......
<service
android:name="com.demo.notification.NotificationService"
android:icon="@drawable/icon"
android:label="@string/app_name" >
</service>
<receiver android:name="com.demo.notification.MyScheduleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
系統開機完成後會發出 BOOT_COMPLETED 廣播,接收器收到後只要把服務拉起來即可:
public class MyScheduleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, NotificationService.class);
context.startService(service);
}
}
public class NotificationService extends Service {
private final IBinder mBinder = new MyBinder();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 將接收推送訊息的任務放入背景執行
new ZeroMQMessageTask().execute();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
public NotificationService getService() {
return NotificationService.this;
}
}
private class ZeroMQMessageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.subscribe(ZMQ.SUBSCRIPTION_ALL);
subscriber.connect("tcp://x.x.x.x:xxxx");
while (true) { // 不終止的迴圈以持續接收訊息
String message = subscriber.recvStr();
if (!message.equals("0")) { // 0 是自訂的空訊息標識
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = "Demo - " + message;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Context uiContext = getApplicationContext();
CharSequence contentTitle = "Demo";
CharSequence contentText = message;
Intent notificationIntent = new Intent(uiContext, NotificationService.class);
PendingIntent contentIntent = PendingIntent
.getActivity(uiContext, 0, notificationIntent, 0);
notification.setLatestEventInfo(uiContext, contentTitle,
contentText, contentIntent);
mNotificationManager.notify(1, notification);
}
}
}
@Override
protected void onPostExecute(String result) {
}
}
}
重啟手機後送出一則訊息,就能在通知列看到它出現在眼前。
這份寫法反映的是早期 Android 的 freely-running 背景服務思維,在今日的系統上會遇到幾道關卡,實作時要一併處理:其一,Android 8.0 起背景執行緒與背景服務受到嚴格限制,長時間連線必須改用前景服務(foreground service)並顯示常駐通知;其二,BOOT_COMPLETED 廣播在部分客製化 ROM 與 Android 8.0 之後的隱式廣播限制下未必送達,需要搭配其他喚醒機制;其三,Notification 的建構方式已改版,setLatestEventInfo() 與舊式建構子皆已移除,必須改用 Notification.Builder 並指定通知管道(channel);其四,while (true) 的無限迴圈在背景執行緒中會讓服務無法被正常回收,實務上應加入停止條件並在 onDestroy() 中收尾。伺服器端的實作可參考 ZeroMQ 的 PUB 發佈端範例。