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 |
<
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();
}
}
}
|
Proactively determine if the screen is lit:
?
1234567 |
public
boolean isScreenOn(Context context) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if
(pm.isScreenOn()) {
return
true
;
}
return
false
;
}
|
Determine if gravity sensing is turned on:
?
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
;
}
|
Android monitor screen unlocks and determines screen status