Background services often need to judge the screen state, if you want to listen to screen unlock event, you can register the action as Android.intent.action.USER_PRESENT broadcast in the configuration, you can listen to unlock events. But sometimes, in the background to perform an operation, you need to actively determine the state of the screen, such as whether it is lit, you can use the PowerManager Isscreenon method to judge, such as whether the screen turned on automatic rotation and so on.
Register the Listener to unlock the broadcast:
| 12345 |
<receiverandroid:name="com.home.testscreen.MyReceiver"> <intent-filter> <actionandroid:name="android.intent.action.USER_PRESENT"/> </intent-filter> </receiver> |
Myreceiver:
?
| 12345678910111213141516171819 |
packagecom.home.testscreen; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.Intent; importandroid.widget.Toast; publicclassMyReceiver extendsBroadcastReceiver { @Override publicvoidonReceive(Context context, Intent intent) { // 解锁 if(intent != null && Intent.ACTION_USER_PRESENT.equals(intent.getAction())) { Toast.makeText(context, "屏幕已解锁", Toast.LENGTH_SHORT).show(); } } } |
Proactively determine if the screen is lit:
?
| 1234567 |
publicboolean isScreenOn(Context context) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if(pm.isScreenOn()) { returntrue; } returnfalse; } |
Determine if gravity sensing is turned on:
?
| 123456789101112131415161718 |
/** * 是否开启了重力感应 * @param context * @return */publicbooleanscreenIsOpenRotate(Context context) { intgravity = 0; try{ gravity = Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION); } catch(SettingNotFoundException e) { e.printStackTrace(); } if(gravity == 1) { returntrue; } returnfalse; } |
Android monitor screen unlocks and determines screen status