Example usage for android.content Intent ACTION_MEDIA_BUTTON

List of usage examples for android.content Intent ACTION_MEDIA_BUTTON

Introduction

In this page you can find the example usage for android.content Intent ACTION_MEDIA_BUTTON.

Prototype

String ACTION_MEDIA_BUTTON

To view the source code for android.content Intent ACTION_MEDIA_BUTTON.

Click Source Link

Document

Broadcast Action: The "Media Button" was pressed.

Usage

From source file:com.devbrackets.android.playlistcore.helper.MediaControlsHelper.java

@NonNull
protected PendingIntent getMediaButtonReceiverPendingIntent(@NonNull ComponentName componentName,
        @NonNull Class<? extends Service> serviceClass) {
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(componentName);

    mediaButtonIntent.putExtra(RECEIVER_EXTRA_CLASS, serviceClass.getName());
    return PendingIntent.getBroadcast(context, 0, mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:androidx.media.session.MediaButtonReceiver.java

/**
 * Extracts any available {@link KeyEvent} from an {@link Intent#ACTION_MEDIA_BUTTON}
 * intent, passing it onto the {@link MediaSessionCompat} using
 * {@link MediaControllerCompat#dispatchMediaButtonEvent(KeyEvent)}, which in turn
 * will trigger callbacks to the {@link MediaSessionCompat.Callback} registered via
 * {@link MediaSessionCompat#setCallback(MediaSessionCompat.Callback)}.
 * @param mediaSessionCompat A {@link MediaSessionCompat} that has a
 *            {@link MediaSessionCompat.Callback} set.
 * @param intent The intent to parse.//w w w.  j  a v  a 2  s.  com
 * @return The extracted {@link KeyEvent} if found, or null.
 */
public static KeyEvent handleIntent(MediaSessionCompat mediaSessionCompat, Intent intent) {
    if (mediaSessionCompat == null || intent == null || !Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())
            || !intent.hasExtra(Intent.EXTRA_KEY_EVENT)) {
        return null;
    }
    KeyEvent ke = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
    MediaControllerCompat mediaController = mediaSessionCompat.getController();
    mediaController.dispatchMediaButtonEvent(ke);
    return ke;
}

From source file:com.smedic.tubtub.BackgroundAudioService.java

/**
 * Initializes media sessions and receives media events
 */// w ww. j av a2  s . c om
private void initMediaSessions() {
    PendingIntent buttonReceiverIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(Intent.ACTION_MEDIA_BUTTON), PendingIntent.FLAG_UPDATE_CURRENT);

    mSession = new MediaSessionCompat(getApplicationContext(), "simple player session", null,
            buttonReceiverIntent);

    try {
        mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());

        mSession.setCallback(new MediaSessionCompat.Callback() {
            @Override
            public void onPlay() {
                super.onPlay();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onPause() {

                super.onPause();
                pauseVideo();
                buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
            }

            @Override
            public void onSkipToNext() {
                super.onSkipToNext();
                playNext();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onSkipToPrevious() {
                super.onSkipToPrevious();
                playPrevious();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onStop() {
                super.onStop();
                stopPlayer();
                //remove notification and stop service
                NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(1);
                Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
                stopService(intent);
            }

            @Override
            public void onSetRating(RatingCompat rating) {
                super.onSetRating(rating);
            }
        });
    } catch (RemoteException re) {
        re.printStackTrace();
    }
}

From source file:com.namelessdev.mpdroid.NotificationService.java

/**
 * This registers some media buttons via the RemoteControlReceiver.class which will take
 * action by intent to this onStartCommand().
 *///from  ww  w  .  j a v a2 s. co  m
private void registerMediaButtons() {
    mMediaButtonReceiverComponent = new ComponentName(this, RemoteControlReceiver.class);
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    final Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intent.setComponent(mMediaButtonReceiverComponent);
    mRemoteControlClient = new RemoteControlClient(PendingIntent.getBroadcast(this /*context*/,
            0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/));

    final int controlFlags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
            | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
            | RemoteControlClient.FLAG_KEY_MEDIA_STOP;

    mRemoteControlClient.setTransportControlFlags(controlFlags);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        enableSeeking(controlFlags);
    }

    mAudioManager.registerRemoteControlClient(mRemoteControlClient);
}

From source file:util.mediamanager.PlaylistUtils.java

public static void ListMediaButtonReceivers(Context context, String query) {

    try {//from   ww w  . j  ava 2  s .co  m

        final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        PackageManager packageManager = context.getPackageManager();

        List<ResolveInfo> mediaReceivers = packageManager.queryBroadcastReceivers(mediaButtonIntent,
                PackageManager.GET_INTENT_FILTERS | PackageManager.GET_RESOLVED_FILTER);

        for (int i = mediaReceivers.size() - 1; i >= 0; i--) {
            ResolveInfo mediaReceiverResolveInfo = mediaReceivers.get(i);
            String name = mediaReceiverResolveInfo.activityInfo.applicationInfo.sourceDir + ", "
                    + mediaReceiverResolveInfo.activityInfo.name;
            String cn = mediaReceiverResolveInfo.resolvePackageName;
            String cn1 = mediaReceiverResolveInfo.activityInfo.toString();
            Log.d(Constants.APP.TAG, "resolvePackageName media receivers = " + cn);
            Log.d(Constants.APP.TAG, "activityInfo = " + cn1);
        }

        mediaButtonIntent.setAction(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
        //mediaButtonIntent.setComponent(new ComponentName("com.spotify.music", "com.spotify.music.MainActivity"));
        mediaButtonIntent.putExtra(SearchManager.QUERY, "GM1");
        mediaButtonIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(mediaButtonIntent);
    } catch (ActivityNotFoundException e) {
        Log.e(Constants.APP.TAG, "Error searching Spotify w/ query '" + query + "'");
        //Toast.makeText(mRideManager.mAppContext, String.format("Error parsing query \"%s\"", query), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

From source file:the.joevlc.AudioService.java

@Override
public void onCreate() {
    super.onCreate();

    // Get libVLC instance
    try {/*ww w .ja v  a2 s . c  o m*/
        mLibVLC = LibVLC.getInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventManager = EventManager.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }

    AudioUtil.prepareCacheFolder(this);
}

From source file:org.videolan.vlc.AudioService.java

@Override
public void onCreate() {
    super.onCreate();

    // Get libVLC instance
    try {/*  w w w . j  av  a  2s  .co m*/
        mLibVLC = Util.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }

    AudioUtil.prepareCacheFolder(this);
}

From source file:com.example.android.supportv4.media.MediaBrowserServiceSupport.java

/**
 * (non-Javadoc)/*from  w  ww  . jav a 2 s. c o  m*/
 *
 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
 */
@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
    if (startIntent != null) {
        String action = startIntent.getAction();
        if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
            MediaButtonReceiver.handleIntent(mSession, startIntent);
        } else if (ACTION_CMD.equals(action)) {
            if (CMD_PAUSE.equals(startIntent.getStringExtra(CMD_NAME))) {
                if (mPlayback != null && mPlayback.isPlaying()) {
                    handlePauseRequest();
                }
            }
        }
    }
    return START_STICKY;
}

From source file:org.videolan.vlc.MediaService.java

@Override
public void onCreate() {
    super.onCreate();

    // Get libVLC instance
    try {// w  w  w  . ja  v  a  2  s . c o m
        mLibVLC = Util.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IMediaServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }

    AudioUtil.prepareCacheFolder(this);
}

From source file:nuclei.media.MediaService.java

@Override
public void onCreate() {
    super.onCreate();
    LOG.d("onCreate");

    mPackageValidator = new PackageValidator(this);

    boolean casting = false;
    try {//from w  w w  . j a  v  a 2 s  .c om
        VideoCastManager.getInstance().addVideoCastConsumer(mCastConsumer);
        casting = VideoCastManager.getInstance().isConnected() || VideoCastManager.getInstance().isConnecting();
    } catch (IllegalStateException err) {
        LOG.e("Error registering cast consumer : " + err.getMessage());
    }

    Playback playback;

    // Start a new MediaSession
    mSession = new MediaSessionCompat(this, "NucleiMediaService",
            new ComponentName(getApplicationContext(), MediaButtonReceiver.class), null);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
    setSessionToken(mSession.getSessionToken());

    try {
        mMediaNotificationManager = new MediaNotificationManager(this);
    } catch (RemoteException e) {
        throw new IllegalStateException("Could not create a MediaNotificationManager", e);
    }

    mSessionExtras = new Bundle();

    if (casting) {
        mSessionExtras.putString(EXTRA_CONNECTED_CAST, VideoCastManager.getInstance().getDeviceName());
        mMediaRouter.setMediaSessionCompat(mSession);
        playback = PlaybackFactory.createCastPlayback(MediaService.this);
    } else
        playback = PlaybackFactory.createLocalPlayback(MediaService.this);

    mPlaybackManager = new PlaybackManager(this, playback);

    mSession.setCallback(mPlaybackManager.getMediaSessionCallback());

    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(new ComponentName(this, MediaService.class));
    mSession.setMediaButtonReceiver(PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0));

    CarHelper.setSlotReservationFlags(mSessionExtras, true, true, true);
    mSession.setExtras(mSessionExtras);

    mPlaybackManager.updatePlaybackState(null, true);

    registerCarConnectionReceiver();
}