如何检查是否单击了耳机中的播放/暂停按钮?在那之后我可以实现一些可以改变我自己的动作(关闭等)的典型动作(播放/暂停)的方法吗?
问问题
10910 次
3 回答
5
现在我正在使用下面的代码耳机按钮单击事件,它对我有用。试试这个代码
// Receiver
public class MediaButtonEventReceiver extends BroadcastReceiver {
private static final String TAG = "MediaButtonIntentReceiv";
public MediaButtonIntentReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Log.e(TAG, "onReceive: " );
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}
// Write this code in onCreateview in your activity
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(1000); //this line sets receiver priority
registerReceiver(r, filter);
// manifest.xml
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter >
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
于 2017-07-28T10:43:18.800 回答
3
如果您试图从前台的活动中侦听此内容,请使用onKeyDown()
并注意KEYCODE_MEDIA_PLAY_PAUSE
.
如果您尝试从后台收听此事件(例如,播放音乐的服务),请使用BroadcastReceiver
for 。ACTION_MEDIA_BUTTON
于 2012-04-12T14:08:51.713 回答
0
您可以使用ACTION_MEDIA_BUTTON意图阅读上面链接的更多信息希望这有帮助
于 2012-04-12T14:02:28.370 回答