Android監聽螢幕解鎖和判斷螢幕狀態
開發後台服務的時候經常需要對螢幕狀態進行判斷,如果是想要監聽螢幕解鎖事件,可以在配置裡面註冊action為 android.intent.action.USER_PRESENT的廣播,則可以監聽解鎖事件。但有時候,在後台執行某個操作時,需要主動判斷螢幕的狀態,比如是否是亮著的,可以使用PowerManager的isScreenOn方法進行判斷,比如螢幕是否開啟了自動旋轉等。
註冊監聽解鎖廣播:
| 12345 |
<receiver android:name="com.home.testscreen.MyReceiver"> <intent-filter> <action android:name="android.intent.action.USER_PRESENT" /> intent-filter> receiver> |
MyReceiver:
?
| 12345678910111213141516171819 |
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(); } } } |
主動判斷螢幕是否亮著:
?
| 1234567 |
public boolean isScreenOn(Context context) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (pm.isScreenOn()) { return true; } return false; } |
判斷是否開啟了重力感應:
?
| 123456789101112131415161718 |
/** * 是否開啟了重力感應 * @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; } |