編輯:關於 Android 程式設計
以 QQ 為例:使用者已經退出 App、甚至 App 不在最近任務清單裡,好友送來的訊息卻仍然能收到並跳通知。要做到這件事,需要一個在介面關閉後仍持續運作、並且與主程式互不影響的常駐元件。
在 AndroidManifest 註冊 Service 時,android:process 決定它跑在哪個進程:
:message):為此 Service 建立一個「本應用私有」的獨立進程。獨立進程的好處是記憶體與生命週期與 UI 脫鉤,主程式被回收時它仍可能存活;代價是進程間溝通要走 Binder、AIDL 或 Messenger,資料不能靠靜態變數傳遞。
package com.example.serverpush;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class ServerPushService extends Service {
private NotificationManager mNotificationManager;
private int mNotificationId = 1000;
@Override
public IBinder onBind(Intent intent) {
return null; // 不需要綁定式服務
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
MessageThread thread = new MessageThread();
thread.setRunning(true);
thread.start();
// START_STICKY:被系統回收後盡量重建
return START_STICKY;
}
/** 定時向伺服器確認是否有新訊息 */
class MessageThread extends Thread {
private volatile boolean mRunning = false;
void setRunning(boolean running) {
mRunning = running;
}
@Override
public void run() {
while (mRunning) {
try {
Thread.sleep(10000); // 實務上應改用 AlarmManager 或長連線
if (!"yes".equals(fetchServerMessage())) {
continue;
}
notifyUser();
} catch (InterruptedException e) {
break;
}
}
}
}
private void notifyUser() {
Intent intent = new Intent(this, MessageActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, mNotificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("您有新訊息")
.setContentText("這是一條新的測試訊息")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
mNotificationManager.notify(mNotificationId++, notification);
}
/** 模擬向伺服器取訊息,實作時替換為真正的網路請求 */
private String fetchServerMessage() {
return "yes";
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
原文使用的 setLatestEventInfo() 早已被移除,Android 4.1 之後必須改用 Notification.Builder(新版為 NotificationCompat.Builder),並在 Android 8.0 以上建立 NotificationChannel,否則通知完全不會顯示。另外,通知 ID 採用自增可避免新訊息互相覆蓋,這點原做法仍然值得沿用。
<!-- 為此應用建立私有獨立進程 -->
<service
android:name=".ServerPushService"
android:process=":message"
android:exported="false" />
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, ServerPushService.class));
}
進入頁面即啟動服務,之後即使關閉介面,:message 進程仍會持續輪詢伺服器並發出通知,這就是「離線推送」的模擬效果。
用常駐進程輪詢的寫法在教學上很好懂,但放在真實產品裡問題不少:Android 8.0 起後台服務受限,Android 9 之後更要求改用 startForegroundService 並顯示常駐通知;Doze 模式與 App Standby 會讓定時任務被大幅延後;各家 ROM 也會主動清理常駐進程。因此正式環境的離線推送應交由 FCM、JPush 這類長連線推送服務,應用端只負責接收與呈現,既省電又穩定。理解輪詢原理有助於除錯,但別把它當成最終方案。
Android 傳感器開發完全解析:分類、框架與實作
Android 裝置內建多種傳感器,可用於偵測動作、環境與位置變化。本文從傳感器分類、Android Sensor Framework 到常見實作,整理出完整的開發脈絡。
Android 開機動畫實作:用 SurfaceView 打造天天果凍風格的圓形擴散 Splash
還記得天天果凍開機時那個相當吸睛的 Splash 動畫嗎?畫面中會有一個空心圓由中心逐漸向外擴散,仔細觀察還會發現,在圓圈擴散的過程中,Logo 本身也伴隨著漸變消失的效
Android 如何防止 APK 被反編譯:ProGuard 設定教學
難堪的现实 身為 Android 應用開發者,不得不面對一個尷尬的局面:自己花無數夜晚做出來的應用,別人幾秒鐘就能反編譯拿走。 Google 顯然也意識到了這個問題。從
Android 項目部署之 Nexus 私服搭建與應用
一、概述 Nexus 是一個基於 Maven 的倉庫管理社區項目,最典型的用場就是在局域網搭建一個 Maven 私服,用來部署第三方公共構件,或作為遠程倉庫在該局域網的代