我有一个扩展LinearLayout
的CustomView,我使用WindowManager.addView()
方法将其添加到屏幕,以使用以下布局参数标记检测我的服务中的关键事件
LinearLayout mLinear = new LinearLayout(getApplicationContext()) {
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
super.dispatchKeyEvent(event);
Log.i(TAG, "event");
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
Log.i("Key", "VolumeUp");
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
Log.i("Key", "VolumeDown");
return true;
case KeyEvent.KEYCODE_BACK:
Log.d(TAG, " " + "KEYCODE_BACK");
return false;
default:
return true;
}
}
};
mView = LayoutInflater.from(this).inflate(R.layout.volume_service_layout, mLinear);
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
if (mView.getVisibility() == View.VISIBLE)
flag = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING ;
//params
params = new WindowManager.LayoutParams(
100,
100,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
wm.addView(mView, params);
}
dispatchKeyEvent()
在customview
课程中被覆盖,但在将其添加到Windows后,请按Button
无法正常工作。当我添加WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
国旗背压按钮正常工作时,我我无法检测到keyup和keydown事件。
我想检测服务类中的keyup或keydown事件。 请为此问题提出任何解决方案。
答案 0 :(得分:0)
我猜您通过使用BroadcastReceiver
来实现这一目标试试这个,
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"...>
//code, like activities, etc
<receiver android:name="com.example.test.VolumeBroadcast" >
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</application>
接收者的例子:
public class VolumeBroadcast extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
//check the intent something like:
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode()) {
// Handle key press.
}
}
}
}
您注册的方式如下:
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
// Start listening for button presses
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
// Stop listening for button presses
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
答案 1 :(得分:0)
在这种情况下,Android不会记录与volume buttons
交互的API。所以我想。这不可能
答案 2 :(得分:-1)
要检测服务中的音量键,请尝试AccessibilityService
并覆盖onkeyEvent()
然后在覆盖事件中完成其余的计算