我有一个运行良好的应用程序,但问题是当它自动进入屏幕锁定模式时,我需要完成一项工作。解锁屏幕我可以检测到使用意图接收器,但无法通过按下电源按钮或自动找到如何知道它何时进入屏幕锁定模式。
有没有办法找到它?我试过跟随但没有运气。
<uses-permission android:name="android.permission.WAKE_LOCK" />
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNjfdhotDimScreen");
@Override
protected void onPause() {
super.onPause();
wl.release();
Toast.makeText(this, "up!!!!." , Toast.LENGTH_LONG).show();
Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}//End of onPause
@Override
protected void onResume() {
super.onResume();
wl.acquire();
Toast.makeText(this, "up!!!!." , Toast.LENGTH_LONG).show();
Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}//End of onResume
编辑:尝试但在 onCreate 下没有运气
KeyguardManager myKM = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
//it is locked
Toast.makeText(this, "up!!!!." , Toast.LENGTH_LONG).show();
Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
} else {
//it is not locked
Toast.makeText(this, "up!!!!." , Toast.LENGTH_LONG).show();
Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
编辑:由于系统性能,您不能用 mainfest 做 3 件事,仍然必须使用以下动态注入。
private BroadcastReceiver mPowerKeyReceiver = null;
private void registBroadcastReceiver() {
final IntentFilter theFilter = new IntentFilter();
/** System Defined Broadcast */
theFilter.addAction(Intent.ACTION_SCREEN_ON);
theFilter.addAction(Intent.ACTION_SCREEN_OFF);
mPowerKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String strAction = intent.getAction();
if (strAction.equals(Intent.ACTION_SCREEN_OFF) || strAction.equals(Intent.ACTION_SCREEN_ON)) {
// > Your playground~!
Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>onDestroy");
}
}
};
getApplicationContext().registerReceiver(mPowerKeyReceiver, theFilter);
}
private void unregisterReceiver() {
int apiLevel = Integer.parseInt(Build.VERSION.SDK);
if (apiLevel >= 7) {
try {
getApplicationContext().unregisterReceiver(mPowerKeyReceiver);
}
catch (IllegalArgumentException e) {
mPowerKeyReceiver = null;
}
}
else {
getApplicationContext().unregisterReceiver(mPowerKeyReceiver);
mPowerKeyReceiver = null;
}
}