Categoryintent

Add Headset button support to your Android application

It’s relatively easy to add headset button support to your application. For example you want to play/pause media playback in your super media player.

But here are a few moments that you should take into consideration:

    1. You should register your broadcast receiver inside your application (not in manifest file). Otherwise Google Music player will catch your broadcast and aboard it. http://android.git.kernel.org/?p=platform/packages/apps/Music.git;a=blob;f=src/com/android/music/MediaButtonIntentReceiver.java
    2. Your IntentFilter priority should be higher that other media players priorities in your phone:) That’s kind of tricky thing.

      The code snippet will look like:

      MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();
      IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
      mediaFilter.setPriority(MEDIA_BUTTON_INTENT_EMPIRICAL_PRIORITY_VALUE);
      registerReceiver(mMediaButtonReceiver, mediaFilter);
      

      And MediaButtonIntentReceiver.java

      public class MediaButtonIntentReceiver extends BroadcastReceiver {
      
          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
              }
              abortBroadcast();
          }
      }
      
      1. Don’t forget to unregister your broadcast receiver
      2. Add “android.permission.BLUETOOTH” permission if you want to support bluetooth headset

      // DL

      How to create calendar event with specific repetition rule

      Just a quick note how to set specific repetition rule when creating new calendar event. I haven’t found any documentation about this and had to inspect platform code.

      Intent intent = new Intent(Intent.ACTION_EDIT);
      intent.setType("vnd.android.cursor.item/event");
      intent.putExtra("beginTime", date);
      intent.putExtra("allDay", true);
      intent.putExtra("rrule", "FREQ=YEARLY");
      intent.putExtra("endTime", date);
      intent.putExtra("title", summary);

      date (long) is time in ms
      allDay means “all day event”
      rrule is the repetition rule in specific format (RFC 2445). In my example “FREQ=YEARLY” means yearly repetition.

      //DL

      © 2019 Android Tales

      Theme by Anders NorenUp ↑