添加意图过滤器:
IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
BroadcastReceiver myReceiver = new MYBCR();
registerReceiver(myReceiver, filter);
您的广播接收器:
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
Log.d("tag", "system dialog close");
}
}
这对我来说很好,它还可以监听每个系统对话框。如果您只想听长按电源按钮,则可以使用 Service 并且在通过开发人员指南后没有找到广播接收器的任何内容。
以下是我对服务的处理方式:
@Override
public void onCreate() {
super.onCreate();
mLinear = new LinearLayout(getApplicationContext()) {
//home or recent button
public void onCloseSystemDialogs(String reason) {
if ("globalactions".equals(reason)) {
Log.d("tag", "Long press on power button");
} else if ("homekey".equals(reason)) {
//home key pressed
} else if ("recentapps".equals(reason)) {
// recent apps button clicked
}
}
};
mLinear.setFocusable(true);
View mView = LayoutInflater.from(this).inflate(R.layout.test, mLinear);
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
//params
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1,
1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
PixelFormat.OPAQUE);
params.gravity = Gravity.TOP | Gravity.LEFT;
wm.addView(mView, params);
}
您将需要一个布局,并确保它是线性布局,仅此而已。即使屏幕锁定,您也可以听到电源长按。
希望这会有所帮助。