Spotify Android Intent Play on Launch

2019-08-07 10:26发布

问题:

I'm trying to get Spotify to resume playback when launched from an intent but not having much luck. I think I'm close I can get Spotify to launch, and if I specify a search for an artist it will auto play but really I just want it to resume what I was last playing which I have not gotten to work yet. This site made it seem possible but with what I have so far Spotify just launches and goes to the search screen. http://developer.android.com/guide/components/intents-common.html#PlaySearch

Here is my code so far:

        final Intent intent1 = new Intent(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
        intent1.setComponent(new ComponentName("com.spotify.music", "com.spotify.music.MainActivity"));
        intent1.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "vnd.android.cursor.item/*");
        intent1.putExtra(SearchManager.QUERY, "");
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (intent1.resolveActivity(getPackageManager()) != null) {
            startActivity(intent1);
        }

回答1:

Took me a while to figure this out so I thought I would post the solution I used. I looped through all the packages that subscribe to Intent.ACTION_MEDIA_BUTTON and that is when I found the component name I needed to get this to work:

private void playPlayMusic() {
    Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
    i.setComponent(new ComponentName("com.spotify.music", "com.spotify.music.internal.receiver.MediaButtonReceiver"));
    i.putExtra(Intent.EXTRA_KEY_EVENT,new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY));
    sendOrderedBroadcast(i, null);

    i = new Intent(Intent.ACTION_MEDIA_BUTTON);
    i.setComponent(new ComponentName("com.spotify.music", "com.spotify.music.internal.receiver.MediaButtonReceiver"));
    i.putExtra(Intent.EXTRA_KEY_EVENT,new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY));
    sendOrderedBroadcast(i, null);
}


回答2:

Here is a routine for searching by Artist and playing in Spotify:

public void playSearchArtist(String artist) {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
    intent.setComponent(new ComponentName("com.spotify.music", "com.spotify.music.MainActivity"));
    intent.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE);
    intent.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
    intent.putExtra(SearchManager.QUERY, artist);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}