我编写了一个像APP一样的常用MediaPlayer。现在我有一对带有内置遥控器的耳机,用于控制音量,暂停和播放歌曲。 我的想法是用这个来控制我的MediaPlayer服务。但我无法在网上找到有关我的问题的任何内容。有人可以给我一个提示吗?
答案 0 :(得分:0)
我不知道为什么我会对我的问题进行投票,但我会为面临同样问题的其他人回答。
tasks.whenTaskAdded {task ->
if(task.name.contains("unwantedTask")) {
task.enabled = false
}
}
在主Activity.onCreate()
中调用此方法public class MediaService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { private IntentFilter intentFilterMediaButton = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); private MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver(); @Override public void onPrepared(MediaPlayer mediaPlayer) { registerReceiver(this.mMediaButtonReceiver, this.intentFilterMediaButton); player.start(); } public static class MediaButtonIntentReceiver extends BroadcastReceiver { @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) { switch (action){ case 0: // Button down // do something Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show(); break; } } abortBroadcast(); } }
并把它放入Manifest
AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);
if (manager != null) {
manager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), MediaService.MediaButtonIntentReceiver.class.getName()));
}