編輯:關於 Android 程式設計
前言:在 Android 四大組件裡,廣播(Broadcast)與服務(Service)堪稱最「低調」的兩個。使用者幾乎感覺不到它們的存在,但它們的身影其實無處不在——簡訊收發、狀態列通知、夜間模式、背景音樂播放,背後都有它們在運作。本文先談廣播,再談服務,並附上可以跑起來的實作範例。
流程只有兩步:先建立 Intent 並設定 Action,再呼叫 sendBroadcast() 或 sendOrderedBroadcast() 發送。
Intent intent = new Intent();
// 這裡使用自訂 Action,記得在 Manifest 中註冊對應的 filter
intent.setAction("com.maiyu.action.MAIYU_BROADCAST");
intent.putExtra("msg", "自定義的廣播");
sendBroadcast(intent);
接著自訂接收器,繼承 BroadcastReceiver 並覆寫 onReceive:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,
"接收到的 Action 為:" + intent.getAction()
+ "\n訊息內容是:" + intent.getStringExtra("msg"),
Toast.LENGTH_SHORT).show();
}
}
最後別忘了在 AndroidManifest.xml 中註冊:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.maiyu.action.MAIYU_BROADCAST" />
</intent-filter>
</receiver>
| 類型 | 發送方法 | 特性 |
|---|---|---|
| 普通廣播 Normal Broadcast | sendBroadcast() | 所有接收器同時收到,無法傳遞處理結果,也無法中斷傳播 |
| 有序廣播 Ordered Broadcast | sendOrderedBroadcast() | 依優先級(IntentFilter.setPriority)由高到低依序傳遞;優先級不足者收不到,高優先級接收後可以選擇中止後續傳播 |
除了靜態宣告,另一種常見做法是在程式碼中用 registerReceiver() 動態註冊,優點是可以隨時開關監聽。以「開機自啟」為例:
class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 開機完成是系統 action
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent newIntent = new Intent(context, FourActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
}
}
}
// 建立接收器
BCreceiver = new BootCompleteReceiver();
// 需要監聽時註冊(三行程式碼可壓縮為一行)
IntentFilter inf = new IntentFilter();
inf.addAction(Intent.ACTION_BOOT_COMPLETED);
registerReceiver(BCreceiver, inf);
// 不再需要時解除註冊
if (BCreceiver != null) {
unregisterReceiver(BCreceiver);
}
動態註冊時,記得在 Manifest 加上權限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
由此可見 registerReceiver() 接收兩個參數:自訂的接收器物件,以及 IntentFilter 物件;而 unregisterReceiver() 只需要傳入接收器物件。
| 場景 | Action |
|---|---|
| 拍照鍵按下 | Intent.ACTION_CAMERA_BUTTON |
| 耳機插入 | Intent.ACTION_HEADSET_PLUG |
| 電量過低 | Intent.ACTION_BATTERY_LOW |
| 電源斷開/接入 | ACTION_POWER_DISCONNECTED / ACTION_POWER_CONNECTED |
| 桌布變更 | Intent.ACTION_WALLPAPER_CHANGED |
| 手機重啟 | Intent.ACTION_REBOOT |
| APK 安裝/卸載 | ACTION_PACKAGE_ADDED / ACTION_PACKAGE_REMOVED |
| SD 卡掛載/卸出 | ACTION_MEDIA_MOUNTED / ACTION_MEDIA_EJECT |
| 系統設定/區域設定變更 | ACTION_CONFIGURATION_CHANGED / ACTION_LOCALE_CHANGED |
| 儲存空間不足 | Intent.ACTION_DEVICE_STORAGE_LOW |
| 鎖屏/解鎖 | ACTION_SCREEN_OFF / ACTION_SCREEN_ON |
| 開機完成 | Intent.ACTION_BOOT_COMPLETED(需權限) |
以上多數寫法完全同構:繼承 BroadcastReceiver、在 onReceive 中比對 Action、動態註冊與解除註冊即可,因此不再逐一貼上重複的程式碼。
飛行模式的處理方式略有不同,需要透過 ContentResolver 修改系統設定並手動發送廣播。佈局上放兩個按鈕:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_startflying"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="開啟飛行模式" />
<Button
android:id="@+id/btn_stopflying"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="關閉飛行模式" />
</LinearLayout>
case R.id.btn_startflying:
// 0 代表關閉,1 代表開啟
if ("0".equals(Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON))) {
Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "1");
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED)
.putExtra("state", true);
sendBroadcast(intent);
Toast.makeText(this, "已開啟飛行模式", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_stopflying:
if ("1".equals(Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON))) {
Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "0");
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED)
.putExtra("state", false);
sendBroadcast(intent);
Toast.makeText(this, "已關閉飛行模式", Toast.LENGTH_SHORT).show();
}
break;
別忘了加上寫入設定的權限:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Service 類似於 Activity,同樣有自己的生命週期,但沒有使用者介面,主要在後台執行較長時間的工作。使用上分兩步:建立子類,然後在 AndroidManifest 中宣告(可透過 <intent-filter> 指定哪些 Intent 能啟動它)。
以 startService() 啟動:
以 bindService() 綁定:
這個範例示範如何用 AlarmManager 搭配 PendingIntent,週期性地啟動廣播或服務。佈局上放四顆按鈕:定時發送廣播、定時啟動服務、停止定時廣播、停止定時服務。
// 取得系統服務
am = (AlarmManager) getSystemService(ALARM_SERVICE);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 啟動:定時廣播
pi1 = PendingIntent.getBroadcast(SecondActivity.this, 0,
new Intent(SecondActivity.this, ActionBroadCast.class),
Intent.FILL_IN_ACTION);
long now = System.currentTimeMillis();
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi1);
// 啟動:定時服務
pi2 = PendingIntent.getService(SecondActivity.this, 0,
new Intent(SecondActivity.this, ActionService.class),
Intent.FILL_IN_ACTION);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi2);
// 停止
am.cancel(pi1);
am.cancel(pi2);
服務端只需要覆寫 onCreate 印出計數,就能觀察到週期性觸發的效果:
public class ActionService extends Service {
private static int num = 0;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.e("ActionService", "New Message ! " + num++);
}
}
廣播接收器同理,在 onReceive 中印出計數即可。這裡刻意使用 setInexactRepeating 而非 setRepeating,因為精確重複鬧鐘會顯著增加電量消耗,Android 也建議開發者優先採用不精確版本,讓系統自行合併調度。
駕車時開啟行車模式(來電自動接聽),夜間則切換到夜間模式。兩者都由系統服務 UiModeManager 負責:
uiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE); // 行車模式 uiModeManager.enableCarMode(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME); uiModeManager.disableCarMode(UiModeManager.DISABLE_CAR_MODE_GO_HOME); // 夜間模式 uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES); uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
佈局上同樣是四顆按鈕,分別對應開啟/關閉行車模式與夜間模式,點擊時呼叫上述方法並用 Toast 提示結果即可。
音量相關操作由 AudioManager 負責。它最有價值的部分是把音量細分為多個 stream:
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// 讀取各類音量
int currentCall = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
int currentSystem = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
int currentMusic = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int currentTip = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
// 調整音量
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
也就是說,「調音量」這件事在 Android 裡並不是單一概念:通話音量、系統提示音、音樂、鬧鐘各自獨立,實作前一定要先想清楚要操作的是哪一條 stream。
廣播與服務的 API 都不算複雜,真正的難點在於「何時該用哪一種」。幾點實務經驗值得記住:
以上都只是基礎入門示範,後續還有更多細節可以深入。待續。
Qt on Android 實踐:通過 JNI 調用系統原生分享菜單
原文《Sharing with Qt on Android》發表於 2014 年 12 月 12 日。當時我寫的遊戲 GiraffPanic(一款用 Qt & Q
Android 阻止 EditText 自動取得焦點的兩個做法
進入頁面時,如果第一個控制項是 EditText,系統預設會自動把焦點給它,順帶彈出軟鍵盤,遮掉半個畫面。這個行為在大多數情況下都不是我們想要的。要阻止它,有兩個互補的做
安卓實作:子線程與主線程的互動(時鐘範例)
這個範例示範如何在子線程中即時產生時間,並透過 Handler 更新到主線程的介面上。 先看版面配置: 主程式如下。子線程每隔一秒產生一次時間資料,透過 Ha
Android 透過廣播異步更新 UI 與 ANR 排查
範例目標 這個範例模擬透過廣播觸發背景工作,再回到主執行緒更新 UI。畫面中有一個 TextView 與一個按鈕,點擊按鈕後送出自訂廣播,BroadcastReceive