在Android设备锁定时检测硬件按钮按下

时间:2017-12-07 04:41:58

标签: android broadcastreceiver

我正在尝试检测硬件按钮按下,特别是在设备锁定时长按电源按钮。我创建了一个BroadcastReceiver,它会在设备锁定时启动。解锁。但是那之后我被困了...... 任何解决方案?

我的代码示例:

<receiver android:name=".Receivers.UnlockReceiver">
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.intent.action.SCREEN_ON" />
                <action android:name="android.intent.action.SCREEN_OFF" />
            </intent-filter>
        </receiver>

接收者类:

public class UnlockReceiver extends BroadcastReceiver {

        private String TAG = "UnlockReceiver";


        @Override
        public void onReceive(final Context context, Intent intent) {
            // Now I'm trying to detect power button 
            // press & long press while the device is locked
        }

    }

1 个答案:

答案 0 :(得分:1)

 @Override
 protected void onPause() {
 super.onPause();

PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);
    boolean isScreenOn = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH)  
      {
        if (powerManager != null)
          {
            isScreenOn = powerManager.isInteractive();
           }
    } 
  else
       {
        if (powerManager != null) 
        {
            isScreenOn = powerManager.isScreenOn();
        }
    }

    if (!isScreenOn) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
        }

        // The screen has been locked

    }
}