Android, BroadcastReceiver, headset controls

Power to opensource!

Because of it I could personalize an app by adding a few lines of code, without reinventing the wheel.

Goal: improve a mediaplayer app to handle headset controls events, even if the screen is off or I’m using another app (there it goes the broadcast receiver functionality).

First, main activity must implement OnKeyListener

...
import .........
...
public class MPlayer extends Activity implements OnKeyListener {...

Second, implement the method OnKeyDown

public ImageButton playButton;
public ImageButton stopButton;
public ImageButton skipButton;
 ....
  oncreate method that instantiates those buttons, by findviewbyid for example
  ....
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
	return false;
}

/* media controls */
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
	case KeyEvent.KEYCODE_MEDIA_NEXT:
		skipButton.performClick();
		return true;
	case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
		stopButton.performClick();
		return true;
	case KeyEvent.KEYCODE_HEADSETHOOK:
		playButton.performClick();
		return true;
		}
		return false;
}

Third, create the receiver

/* creating an intent filter */
private final BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
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);
	int keycode = event.getKeyCode();
	int action = event.getAction();
	Log.i("keycode", String.valueOf(keycode));
	Log.i("action", String.valueOf(action));
                 //onKeyDown(keyCode, event)
	if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
			|| keycode == KeyEvent.KEYCODE_HEADSETHOOK)
			if (action == KeyEvent.ACTION_DOWN)
				playButton.performClick();
	if (keycode == KeyEvent.KEYCODE_MEDIA_NEXT)
			if (action == KeyEvent.ACTION_DOWN)
				skipButton.performClick();
	if (keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS)
			if (action == KeyEvent.ACTION_DOWN)
				stopButton.performClick();

		}

};

/* unregistering intent receiver */

public void onDestroy() {
	super.onDestroy();
	unregisterReceiver(headsetReceiver);
}

Last, registering the intent receiver in onCreate method

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
		/* creating and registering intent receiver */
	IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
	mediaFilter.setPriority(1000);
	registerReceiver(headsetReceiver, mediaFilter);
         ....
         ....

Last but not least, even if you declare and register the intent receiver via code, you can also add a couple of lines of code in your app manifest

<activity android:name=".MPlayer" android:label="@string/app_name">
	<intent-filter>
		<action android:name="android.intent.action.MAIN" />
		<category android:name="android.intent.category.LAUNCHER" />
	</intent-filter>
	<intent-filter android:priority="1000000000">
		<action android:name="android.intent.action.MEDIA_BUTTON" />
	</intent-filter>
</activity>
 
 
 
 

Sources: various( I mean VARIOUS, like ALOT) android articles, android developers docs and google results and my working app. Headset finally plugged in and controls being used!

5 thoughts on “Android, BroadcastReceiver, headset controls

    • Thanks for your feedback, it makes me feel that something that I do with pleasure is going to help other people! thanks again, see you soon and in the meantime have a good life!

    • Ci puoi scommettere! L’occasione fa l’uomo ragno, sfruttiamo questi bei commenti togliendo i link brutti che si portano con se😉 Generico Spammer sei furbo, io di più!

  1. Great post, it helped me to understand how to know which button was pressed, but what if I don’t want a media button, this is because sometimes when I press media buttons another app is opened like Spotify or google media player, even if I give high priority to my app, beside I don’t want to be “fighting” with other apps to open mine instead them, so it’s possible to create an intent for a custom button instead media_button?

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...