Android 监听耳机按钮输入不起作用
根据我在网上阅读的多个其他问题,当收听耳机按钮输入时,你应该有一个媒体按钮操作的接收器,并在你的清单中注册该接收器。Android 监听耳机按钮输入不起作用,android,android-studio,headset,Android,Android Studio,Headset,根据我在网上阅读的多个其他问题,当收听耳机按钮输入时,你应该有一个媒体按钮操作的接收器,并在你的清单中注册该接收器。 我的代码如下: (舱单) 其中接收器位于名为侦听器的包中 但是,我无法通过执行此操作或执行在线发现的某些修复来让日志正常工作(请将筛选器的优先级设置为非常高,尝试在代码中而不是在清单中设置接收器依赖项) 我知道按钮输入本身是有效的,因为我尝试在我的活动中覆盖onKeyDown函数,它确实在那里运行。但是,即使活动不是当前窗口,我也希望能够听到单击声。 如果需要的话,我的目标SDK
我的代码如下:
(舱单) 其中接收器位于名为
侦听器的包中
但是,我无法通过执行此操作或执行在线发现的某些修复来让日志正常工作(请将筛选器的优先级设置为非常高,尝试在代码中而不是在清单中设置接收器依赖项)
我知道按钮输入本身是有效的,因为我尝试在我的活动中覆盖onKeyDown
函数,它确实在那里运行。但是,即使活动不是当前窗口,我也希望能够听到单击声。
如果需要的话,我的目标SDK版本是API 25(7.1.1)。您可以尝试支持库提供的广播接收器,而不是创建自己的广播接收器
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
服务的实施
public class MediaPlaybackService extends Service {
private MediaSessionCompat mediaSessionCompat;
private static final String TAG = "MediaPlaybackService";
@Override
public void onCreate() {
super.onCreate();
mediaSessionCompat = new MediaSessionCompat(this, "myMediaSession");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: media button intent");
MediaButtonReceiver.handleIntent(mediaSessionCompat, intent);
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
<service android:name=".MediaPlaybackService">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</service>
public class MediaPlaybackService extends Service {
private MediaSessionCompat mediaSessionCompat;
private static final String TAG = "MediaPlaybackService";
@Override
public void onCreate() {
super.onCreate();
mediaSessionCompat = new MediaSessionCompat(this, "myMediaSession");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: media button intent");
MediaButtonReceiver.handleIntent(mediaSessionCompat, intent);
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}