編輯:關於 Android 程式設計
先來看效果。

點擊通知之後的樣子:

public class TextActivity extends Activity {
Button button;
Button buttonstop;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
buttonstop = (Button) findViewById(R.id.titlebutton);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setAction(com.text.ac.action.MY_SERVICE);
startService(intent);
}
});
buttonstop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setAction(com.text.ac.action.MY_SERVICE);
stopService(intent);
}
});
}
}
這裡用顯式 Intent 的 setAction 而非指定 class,屬於比較鬆散的耦合方式。實務上更推薦直接 new Intent(this, MessageService.class),行為明確也不容易被其他元件攔截。
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.ic_hehe;
messageNotification.tickerText = "新訊息";
messageNotification.defaults = Notification.DEFAULT_SOUND;
messageNotificatioManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
messageIntent = new Intent(this, TextActivity.class);
messagePendingIntent = PendingIntent.getActivity(this, 0, messageIntent, 0);
messageThread = new MessageThread();
messageThread.isRunning = true;
messageThread.start();
Toast.makeText(MessageService.this, "aaaa", Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public void onDestroy() {
messageThread.isRunning = false;
super.onDestroy();
}
public String getServerMessage() {
return "不錯哦";
}
}
class MessageThread extends Thread {
public boolean isRunning = true;
public void run() {
while (isRunning) {
try {
Thread.sleep(5000);
String serverMessage = getServerMessage();
if (serverMessage != null and !"".equals(serverMessage)) {
messageNotification.setLatestEventInfo(
MessageService.this,
"新訊息",
"您中獎了,500萬!" + serverMessage,
messagePendingIntent);
messageNotificatioManager.notify(
messageNotificationID, messageNotification);
messageNotificationID++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
兩個設計細節值得說明。第一,通知 ID 每次遞增,目的是避免新訊息覆蓋舊訊息——若固定使用同一個 ID,後到的通知會直接把前面的頂掉。第二,onDestroy 中把 isRunning 設為 false 讓迴圈退出,這是讓線程優雅結束的必要步驟;若不這麼做,Service 銷毀了但線程還在跑,就會造成洩漏。
它適合理解原理,但直接搬到專案裡會遇到麻煩,這裡誠實列出來:
1. setLatestEventInfo 與直接 new Notification() 這套寫法在 API 26 之後已不適用。新版本必須使用 NotificationCompat.Builder 搭配 NotificationChannel,否則通知根本不會顯示。
2. 後台 Service 在 Android 8.0 之後受限嚴格,長時間運行需要改為前景服務(startForeground)並顯示常駐通知,或使用 WorkManager 這類由系統調度的方案。
3. 用 Thread.sleep 做輪詢既耗電又不可靠,實際的推送應該由服務端主動下發,客戶端透過長連線(WebSocket、MQTT)或各家廠商的推送服務接收。
4. PendingIntent.getActivity 在 Android 12 之後必須顯式聲明 FLAG_IMMUTABLE 或 FLAG_MUTABLE,否則會拋出例外。
5. super.onCreate() 應該放在方法開頭而非結尾,這是 Android 生命週期方法的通用約定。
理解「Service 跑背景邏輯、NotificationManager 負責呈現、PendingIntent 處理點擊跳轉」這三者的分工,是這份程式碼真正的價值所在;具體 API 則建議對照當前版本的官方文件重寫。
Android drawable 資料夾怎麼選?一次搞懂 mdpi、hdpi 與圖片縮放的關係
寫一個小遊戲,程式碼檢查了三遍都沒發現問題,可主界面上有幾張圖片就是莫名其妙地比設計稿大了一號。最後的解法荒唐得讓人哭笑不得——把圖片從 drawable-mdpi 換到
Android 開發技巧:如何自行控制 Toast 的顯示與關閉
先解釋一個常見疑問:為什麼 Toast 顯示一段時間後會自動消失? 因為 Android 系統內部維護著一個 Toast 佇列,系統會依序從中取出一個 Toast 顯示
Android WebView 入門:核心概念、必要設定與常用載入方式
一、WebView 與 WebKit Android 系統內建了一款高效能的 WebKit 核心瀏覽器,SDK 把它封裝成 WebView 元件。 WebKit 起源於
Android 資料儲存入門:內部檔案的讀與寫
Android 為開發者準備了幾套資料持久化方案:檔案儲存、SharedPreferences、SQLite 資料庫,另外還可以把資料寫到外接儲存(SD 卡)。其中檔案儲