韌館-LearnHouse

[Android]監聽螢幕狀態與主動喚醒螢幕

由於需要APP能在Android TV進入sleep mode後還能透過網路被喚醒並播放聲音,經過一陣子的survey,發現可以用以下的方法來達到效果,先用wake lock喚醒螢幕再播放聲音。
首先要加入權限

<uses-permission android:name="android.permission.WAKE_LOCK" />


撰寫喚醒螢幕的程式:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
    isScreenOn = powerManager.isInteractive();
} else {
    isScreenOn = powerManager.isScreenOn();
}
if (!isScreenOn) {
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
            | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, MyService.class.getName());
    wakeLock.acquire();
    if (wakeLock != null) {
        wakeLock.acquire(1000);
        wakeLock.release();
    }
}

這裡要注意的是,PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK兩個要同時存在,只有寫任一一個都不會有效果。
再來透過監聽螢幕的狀態來決定是否需要喚醒螢幕

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_ON) ) {
            Log.d(TAG, "Screen On");
        }
        else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            Log.d(TAG, "Screen Off");
        }
    }
};

IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(receiver, filter);
2021年1 月 posted by admin in 程式&軟體 and have No Comments

Place your comment

Please fill your data and comment below.
名稱:
信箱:
網站:
您的評論: