安卓-我如何检测安卓将进入屏幕锁定模式,在那里我需要在那个阶段完成一项工作



我有一个运行良好的应用程序,但问题是当它自动进入屏幕锁定模式时,我需要完成一项工作。解锁屏幕我可以使用意向接收器检测,但无法找到如何知道它何时通过电源按钮按下或自动进入屏幕锁定模式。

有办法找到它吗?我试过追随,但没有成功。

<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做三件事,要做到这一点,必须使用以下动态注入。

  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;
      }
  }

也许您可以将广播接收器用于"android.intent.action.SCREEN_ON"one_answers"android.ntent.action.SCREEN_OFF".

最新更新