ACTION_SCREEN_ON 和 ACTION_SCREEN_OFF 為**受保護廣播**,**只能動態註冊**(Context.registerReceiver()),**不可在 Manifest 中靜態聲明**。系統為節省電量,限制只有運行中的組件才能接收。
public class ScreenActionReceiver extends BroadcastReceiver {
private static final String TAG = "ScreenActionReceiver";
private boolean isRegistered = false;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action)) {
Log.d(TAG, "螢幕解鎖");
// 執行解鎖邏輯:恢復監聽、重新連接網絡等
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
Log.d(TAG, "螢幕鎖定");
// 執行鎖定邏輯:暫停播放、釋放資源等
}
}
public void register(Context context) {
if (!isRegistered) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
context.registerReceiver(this, filter);
isRegistered = true;
Log.d(TAG, "廣播接收器已註冊");
}
}
public void unregister(Context context) {
if (isRegistered) {
context.unregisterReceiver(this);
isRegistered = false;
Log.d(TAG, "廣播接收器已註銷");
}
}
}
| 場景 | 註冊時機 | 註銷時機 |
|---|---|---|
| 全局監聽(如鎖屏播放控制) | Application.onCreate() 或 主 Activity.onCreate() | Application.onTerminate()(僅模擬器)或進程死亡自動清理 |
| 頁面級監聽(如輸入法顯示邏輯) | Activity.onResume() | Activity.onPause() |
| Service 長期監聽 | Service.onCreate() | Service.onDestroy() |
isRegistered 防止多次註冊導致 IllegalArgumentException。unregisterReceiver,否則洩漏並崩潰。onReceive 運行在主線程,**嚴禁耗時邏輯**(網絡請求、DB 操作),應派發到工作線程或啟動 Service 處理。WakeLock(PARTIAL_WAKE_LOCK)。Android 10 (API 29) 後,後台應用無法直接啟動 Activity。若在鎖屏廣播中嘗試啟動 UI,需滿足「從後台啟動 Activity 的條件」(如有系統窗口權限、來電等),否則會拋出 SecurityException。建議改用高優先級通知或 Foreground Service。