I want to call a function im my service class when I press the headset button. Therefor I needed to implement a static inner broadcast class into my service. But now I cannot access the local field of the MediaPlayer that is currently running because I have to stay static. I tried it with observable but that didnt work either. Like in this answer
I tried also to make the field itself static, but in the logic I want to implement, I need a function that switches songs so I would have to set the playlist also static and that is not acceptable for me.
public class MediaService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
private IntentFilter intentFilterMediaButton = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
private MediaButtonReceiver mMediaButtonReceiver = new MediaButtonReceiver();
public MediaPlayer player;
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
registerReceiver(this.mMediaButtonReceiver, this.intentFilterMediaButton);
player.start();
}
static int xTime = 0;
public static class MediaButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(final 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
xTime++;
Handler handler = new Handler();
Runnable run = new Runnable() {
@Override
public void run() {
if(xTime == 1)
//MediaService.mediaControlAction(xTime);
if(xTime == 2)
//MediaService.mediaControlAction(xTime);
xTime = 0;
}
};
if(xTime == 1)
handler.postDelayed(run, 500);
break;
}
}
abortBroadcast();
}
}
}