-1

I have programmed an usual MediaPlayer like APP. Now I have a pair of headphones with inline remote controls for Controlling the volume, pause and Play Songs. My idea is to Control my MediaPlayer Service with this. But I cant find anything on the web concerning my Problem. Can somebody might give me a hint to this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
nixn
  • 1,337
  • 3
  • 16
  • 33

1 Answers1

0

I dont know why I get downvoted with my question, but I will answer it for others facing the same Problem.

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();
    }
}

Called this in the main activity.onCreate()

    AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (manager != null) {
        manager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), MediaService.MediaButtonIntentReceiver.class.getName()));
    }

And put this into the Manifest

    <receiver android:name="MediaService$MediaButtonIntentReceiver" android:enabled="true">
        <intent-filter android:priority="1000000000">
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>
nixn
  • 1,337
  • 3
  • 16
  • 33