Android listens to screen unlocking and determines screen status
When developing background services, you often need to determine the screen status. If you want to listen to screen unlocking events, you can register the action as android in the configuration. intent. action. USER_PRESENT broadcast, you can listen to the unlock event. But sometimes, when performing an operation in the background, you need to take the initiative to determine the status of the screen, for example, whether the screen is on, you can use the PowerManager isScreenOn method to determine whether the screen is automatically rotated.
Register the listener to unlock the broadcast:
| 12345 |
<receiver android:name="com.home.testscreen.MyReceiver"> <intent-filter> <action android:name="android.intent.action.USER_PRESENT" /> intent-filter> receiver> |
Mycycler:
?
| 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) { // Unlock if (intent != null && Intent.ACTION_USER_PRESENT.equals(intent.getAction())) { Toast.makeText(context, "Screen unlocked", Toast.LENGTH_SHORT).show(); } } } |
Actively judge whether the screen is on:
?
| 1234567 |
public boolean isScreenOn(Context context) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (pm.isScreenOn()) { return true; } return false; } |
Determine whether gravity sensing is Enabled:
?
| 123456789101112131415161718 |
/** * Whether gravity sensing is enabled * @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; } |