開發後臺服務的時候經常需要對螢幕狀態進行判斷,如果是想要監聽螢幕解鎖事件,可以在配置裡面註冊action為 android.intent.action.USER_PRESENT的廣播,則可以監聽解鎖事件。但有時候,在後臺執行某個操作時,需要主動判斷螢幕的狀態,比如是否是亮著的,可以使用PowerManager的isScreenOn方法進行判斷,比如螢幕是否開啟了自動旋轉等。

註冊監聽解鎖廣播:


<receiver android:name="com.home.testscreen.MyReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>

MyReceiver:


package com.home.testscreen;

import android.content.BroadcastReceiver;
import android.content.CoNtext;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(CoNtext coNtext, Intent intent) {
解鎖
if (intent != null
&& Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {
Toast.makeText(coNtext, "螢幕已解鎖", Toast.LENGTH_SHORT).show();
}
}

}
主動判斷螢幕是否亮著:

public boolean isScreenOn(CoNtext coNtext) {
PowerManager pm = (PowerManager) coNtext.getSystemService(CoNtext.POWER_SERVICE);
if (pm.isScreenOn()) {
return true;
}
return false;
}

判斷是否開啟了重力感應:

/**
* 是否開啟了重力感應
* @param coNtext
* @return
*/
public boolean screenIsOpenRotate(CoNtext coNtext) {
int gravity = 0;
try {
gravity = Settings.System.getInt(coNtext.getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (gravity == 1) {
return true;
}
return false;
}

 
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()