This tutorial leads you step-by-step through the creation of a simple app that uses the App Remote SDK to play a playlist and subscribe to player state updates.

Please note: the Spotify App Remote SDK is currently a beta release; its content and functionality is likely to change significantly without warning. Note that by using Spotify developer tools, you accept our Developer Terms of Use.

Introduction

This tutorial leads you step-by-step through the creation of a simple app that uses the Spotify App Remote SDK to play a playlist. We show you how to:

  • Play a playlist from a URI
  • Subscribe to PlayerState of the Spotify app and read its data

If you are new to developing Android apps, we recommend reading the tutorials on Google’s Android developer portal.

You can read more about the App Remote SDK in the overview, or dig into the reference documentation.

Prepare Your Environment

Register Your App

You will need to register your application on the Developer Dashboard and obtain a client ID. When you register your app you will also need to whitelist a redirect URI that the Spotify Accounts Service will use to callback to your app after authorization. You also should add your package name and app fingerprint as they’re used to verify the identity of your application.

Install Spotify App

Install the latest version of Spotify from Google Play on the device you want to use for development. Run the Spotify app and login or sign up.

Download the SDK

Download the Spotify App Remote SDK from our GitHub.

Create Your App

Create or make sure you have an Android app with at least one Activity or Service in which you can put your code to connect to Spotify.

Your MainActivity should look like this:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // We will write our code here.
    }
}

Add the App Remote SDK

Unzip the App Remote SDK zip file that you downloaded. Add the library to your project by importing it as a module. In the “Project” side bar in Android Studio (View –> Tool Windows –> Project), right click your project’s root folder and navigate to “New” –> “Module”.

New module GUI

In the “New Module” window, choose the option “Import .JAR/AAR Package”. Click “Next”.

Import Jar GUI

Press the “…” button and locate the spotify-app-remote-release-version.aar under the “app-remote-lib” folder in the unzipped bundle. Click “Open” and choose a suitable subproject name. We’re using spotify-app-remote in this example. Click “Finish” to import the .aar into your project.

Create new module GUI

Tip: when updating the App Remote SDK with future updates of the SDK, simply replace the .aar file in your project’s directory.

Add a dependency on the spotify-app-remote module to your app by adding the imported subproject and Gson to your app’s build.gradle file. It is important that the name that you specify in the build.gradle file is the same as the subproject name you decided on.

dependencies {
    // your app dependencies
    compile project(':spotify-app-remote')
    compile "com.google.code.gson:gson:2.6.1"
}

Since version 0.2.0 of the App Remote SDK, Gson is used by default for serializing and deserializing the request. Jackson is also supported. If you would like to use Jackson instead please see the FAQ here.

Import Dependencies

import com.spotify.android.appremote.api.ConnectionParams;
import com.spotify.android.appremote.api.Connector;
import com.spotify.android.appremote.api.SpotifyAppRemote;

import com.spotify.protocol.client.Subscription;
import com.spotify.protocol.types.PlayerContext;
import com.spotify.protocol.types.PlayerState;
import com.spotify.protocol.types.Track;

Set up your Spotify credentials

private static final String CLIENT_ID = "your_client_id";
private static final String REDIRECT_URI = "com.yourdomain.yourapp://callback";
private SpotifyAppRemote mSpotifyAppRemote;

Authorize Your Application

To be able to use the App Remote SDK the user needs to authorize your application. If they haven’t, the connection will fail with UserNotAuthorizedException. To allow user to authorize your app, you can either use Single Sign-On flow described in the Android Authentication and Authorization Guide or the App Remote SDK’s built-in auth flow. This single sign-on approach can be useful if your application needs a token with multiple scopes. If you’re only interested in using the App Remote SDK, you can use the built-in authorization flow. We will use the built-in authorization in this Quick Start.

Authorizing the user using the built-in auth flow

In this flow you don’t have to add the Authorization Library to your application. You can request authorization view to be shown to users who haven’t approved the app-remote-control scope by passing the flag showAuthView in the ConnectionParams. The scope is automatically requested for you by the library.

Add the following to your onCreate method:

// Set the connection parameters
ConnectionParams connectionParams =
    new ConnectionParams.Builder(CLIENT_ID)
            .setRedirectUri(REDIRECT_URI)
            .showAuthView(true)
            .build();

Authorizing user with Single Sign-On library

Download and add Authorization Library to your project as described in this guide. Create and send the authorization request as described in the Android SDK Authorization Guide. You need the app-remote-control scope to use the Spotify App Remote SDK.

Connect to App Remote

The first thing we need to do is to use the SpotifyAppRemote.Connector to connect to Spotify and get an instance of SpotifyAppRemote. To do this, we call the SpotifyAppRemote.CONNECTOR.connect method using the connectionParams we defined above. Add the following to your onCreate method.

SpotifyAppRemote.CONNECTOR.connect(this, connectionParams,
    new Connector.ConnectionListener() {

    @Override
    public void onConnected(SpotifyAppRemote spotifyAppRemote) {
        mSpotifyAppRemote = spotifyAppRemote;
        // Interact with App Remote here
    }

    @Override
    public void onFailure(Throwable throwable) {
        // Handle errors here
        Log.e("MyActivity", throwable.getMessage(), throwable);
    }
});

Play a Playlist

To play a playlist given a Spotify playlist URI, we are going to connect to the Spotify app and use the PlayerApi command. From there we can get the PlayerApi directly and call play. Add the following to your onConnected method:

// Play a playlist
mSpotifyAppRemote.getPlayerApi().play("spotify:user:spotify:playlist:37i9dQZF1DX2sUQwD7tbmL");

Run the application and you should hear some feel-good indie tunes playing on your phone. If you prefer something more relaxing, why not try some sweet piano music spotify:user:spotify:playlist:37i9dQZF1DX7K31D69s4M1. If you don’t hear music playing and end up in the onFailure callback above, please read up on connection errors and try again.

Subscribe to Player State

The PlayerApi offers, in addition to the play(uri) method we use above, the ability to subscribe to and poll for the state of the Spotify player. Add the following to your code to subscribe to PlayerState and log the track title and artist of the song that will be playing:

// Subscribe to PlayerState
mSpotifyAppRemote.getPlayerApi()
    .subscribeToPlayerState().setEventCallback(new Subscription.EventCallback<PlayerState>() {
        @Override
        public void onEvent(PlayerState playerState) {
            final Track track = playerState.track;
            if (track != null) {
            Log.d("MainActivity", track.name + " by " + track.artist.name);
            }
        }
    });
}

Run the app again. You should now see a log with the track name and artist of the currently playing track.

Next Steps

Congratulations! You’ve interacted with the App Remote SDK for the first time. Time to celebrate, you did a great job! 👏

Want more? Here’s what you can do next:

  • Learn about how the App Remote SDK interacts with the Android application lifecycle in our guide.
  • Dive into other things you can do with the SDK in the App Remote SDK Reference.

Source Code

The Quick Start source code is below. Copy into your Main Activity.

package com.yourdomain.yourapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import com.spotify.android.appremote.api.ConnectionParams;
import com.spotify.android.appremote.api.Connector;
import com.spotify.android.appremote.api.SpotifyAppRemote;

import com.spotify.protocol.client.Subscription;
import com.spotify.protocol.types.PlayerContext;
import com.spotify.protocol.types.PlayerState;
import com.spotify.protocol.types.Track;

public class MainActivity extends AppCompatActivity {

    private static final String CLIENT_ID = "your_client_id";
    private static final String REDIRECT_URI = "com.yourdomain.yourapp://callback";
    private SpotifyAppRemote mSpotifyAppRemote;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConnectionParams connectionParams =
                new ConnectionParams.Builder(CLIENT_ID)
                        .setRedirectUri(REDIRECT_URI)
                        .showAuthView(true)
                        .build();

        SpotifyAppRemote.CONNECTOR.connect(this, connectionParams,
                new Connector.ConnectionListener() {

                    public void onConnected(SpotifyAppRemote spotifyAppRemote) {
                        mSpotifyAppRemote = spotifyAppRemote;
                        // Interact with App Remote here
                        Log.d("onConnected", "hey");

                        // Play a playlist
                        mSpotifyAppRemote.getPlayerApi().play("spotify:user:spotify:playlist:37i9dQZF1DX2sUQwD7tbmL");

                        // Subscribe to PlayerState
                        mSpotifyAppRemote.getPlayerApi()
                                .subscribeToPlayerState().setEventCallback(new Subscription.EventCallback<PlayerState>() {

                            public void onEvent(PlayerState playerState) {
                                final Track track = playerState.track;
                                if (track != null) {
                                    Log.d("MainActivity", track.name + " by " + track.artist.name);
                                }
                            }
                        });
                    }

                    public void onFailure(Throwable throwable) {
                        // Handle errors here
                        Log.e("MyActivity", throwable.getMessage(), throwable);
                    }
        });
    }

    protected void onDestroy() {
        super.onDestroy();
        SpotifyAppRemote.CONNECTOR.disconnect(mSpotifyAppRemote);
    }
}