问题
I want to detect volume button press when app is in background and even if device is locked I am working on android P, I was able to get long pressed volume button when app is in background but screen not locked using service and by getting Allow over other apps permission but it caused problem , when app is in background back button and keyboard are not working , I am able to open other apps like whatsapp but I can not type a message and can not back , Here is my code any please help . Thanks in advance.
I have used reference from here to reach to this code Detect power button long press
@Override
public void onCreate(){
super.onCreate();
LinearLayout mLinear= new LinearLayout(PowerButtonService.this){
//home or recent button
public void onCloseSystemDialogs(String reason) {
if ("globalactions".equals(reason)) {
Log.i("Key", "Long press on power button");
} else if ("homekey".equals(reason)) {
//home key pressed
} else if ("recentapps".equals(reason)) {
// recent apps button clicked
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
|| event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP
|| event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.getKeyCode() == KeyEvent.KEYCODE_CAMERA
|| event.getKeyCode() == KeyEvent.KEYCODE_POWER)
{
Log.i("Key", "keycode " + event.getKeyCode());
if(event.getKeyCode()==24){
Application_Class.COUNT++;
Log.i("Count",""+Application_Class.COUNT);
}
}
return super.dispatchKeyEvent(event);
}
};
mLinear.setFocusable(true);
View mView= LayoutInflater.from(this).inflate(
R.layout.service_layout, mLinear);
WindowManager wm = (WindowManager)
getSystemService(WINDOW_SERVICE);
//params
WindowManager.LayoutParams params = new
WindowManager.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
|WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
wm.addView(mView, params);
}
I expect to detect volume or power button press when app is in background or even if device is locked and it should not cause any kind of ambiguity like back button or keyboard not working. Any kind of information and answer will be helpful. Please help.
来源:https://stackoverflow.com/questions/56940062/how-can-i-detect-long-pressed-volume-and-power-button-when-app-is-in-background