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

the Spotify Android 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 Android 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.

Register App Fingerprints

Fingerprints are used for authentication between your Android Application and the Spotify service. You’ll need to generate a fingerprint for your app and register it in your Dashboard. We strongly recommend that you create both a development and a production fingerprint for security reasons.

To Create a Development Fingerprint

  1. Run the following command in your Terminal and add a password when required:

    # On Bash style shells
    $ keytool -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v | grep SHA1
    
    # On Windows Powershell
    $ keytool -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore -list -v | grep SHA1
    

    You should expect to receive a fingerprint that looks like this: SHA1: E7:47:B5:45:71:A9:B4:47:EA:AD:21:D7:7C:A2:8D:B4:89:1C:BF:75

  2. Copy the fingerprint and your package name and enter it in the Spotify Developer Dashboard, under the “Edit settings” section. Don’t forget to click Save after you added the fingerprints in the dashboard.

    Android Packages

To Create a Release Fingerprint

The development and production versions of your application usually have different certificates for security reasons.

  1. Run the following command in your Terminal (no password):

    # On Bash style shells
    $ keytool -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEYSTORE_PATH> -list -v | grep SHA1
    
    # On Windows Powershell
    $ keytool -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEYSTORE_PATH> -list -v | grep SHA1
    

    You should expect to receive a fingerprint that looks like this: SHA1: E7:47:B5:45:71:A9:B4:47:EA:AD:21:D7:7C:A2:8D:B4:89:1C:BF:75

  2. Copy the fingerprint and your package name and enter it in the Spotify Developer Dashboard. Don’t forget to click Save after you added the fingerprints in the dashboard.

Install Spotify App

App Remote SDK requires the Spotify app to be installed on the device. 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 Android 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.

Edit your MainActivity to look like this:

public class MainActivity extends AppCompatActivity {

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

    @Override
    protected void onStart() {
        super.onStart();
        // We will start writing our code here.
    }

    private void connected() {
        // Then we will write some more code here.
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Aaand we will finish off 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
    implementation project(':spotify-app-remote')
    implementation "com.google.code.gson:gson:2.8.5"
}

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.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 = "http://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 to do so. If they haven’t, the connection will fail with UserNotAuthorizedException. To allow the user to authorize your app, you will use the built-in authorization described below.

The built-in authorization flow is an authorization method designed to make things easier for you. It only requires you to pass the corresponding parameters that you used when your application was created. Then, the Spotify client will attempt to authorize your app’s session and will use the ConnectionListener callback to send the authorization result.

For this use-case, you don’t have to add the Authorization Library to your application. You can request that the authorization view is shown to users who have not 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 onStart method:

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

Built-in auth provides offline support. This means that a user can be authorized even if the device is currently offline. Offline support works out of the box, so it doesn’t require any additional implementation.

To successfully authorize a user while offline, the following conditions have to be met:

  • Your application has successfully connected to Spotify within the last 24 hours
  • Your application uses the same redirect URI, client ID and scopes when connecting to Spotify

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.connect method using the connectionParams we defined above. Add the following to your onStart method.

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

    @Override
    public void onConnected(SpotifyAppRemote spotifyAppRemote) {
        mSpotifyAppRemote = spotifyAppRemote;
        Log.d("MainActivity", "Connected! Yay!");

        // Now you can start interacting with App Remote
        connected();
    }

    @Override
    public void onFailure(Throwable throwable) {
        Log.e("MainActivity", throwable.getMessage(), throwable);

        // Something went wrong when attempting to connect! Handle errors here
    }
});

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 private connected method:

// Play a playlist
mSpotifyAppRemote.getPlayerApi().play("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: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 PlayerState

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(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.

Disconnecting from App Remote

Don’t forget to disconnect from App Remote when you no longer need it. Add the following to your onStop method.

@Override
protected void onStop() {
    super.onStop();
    SpotifyAppRemote.disconnect(mSpotifyAppRemote);
}

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:

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.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);
}

    @Override
    protected void onStart() {
        super.onStart();
        ConnectionParams connectionParams =
                new ConnectionParams.Builder(CLIENT_ID)
                        .setRedirectUri(REDIRECT_URI)
                        .showAuthView(true)
                        .build();

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

                    public void onConnected(SpotifyAppRemote spotifyAppRemote) {
                        mSpotifyAppRemote = spotifyAppRemote;
                        Log.d("MainActivity", "Connected! Yay!");

                        // Now you can start interacting with App Remote
                        connected();

                    }

                    public void onFailure(Throwable throwable) {
                        Log.e("MyActivity", throwable.getMessage(), throwable);

                        // Something went wrong when attempting to connect! Handle errors here
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        SpotifyAppRemote.disconnect(mSpotifyAppRemote);
    }

    private void connected() {
        // Play a playlist
        mSpotifyAppRemote.getPlayerApi().play("spotify:playlist:37i9dQZF1DX2sUQwD7tbmL");

        // Subscribe to PlayerState
        mSpotifyAppRemote.getPlayerApi()
                .subscribeToPlayerState()
                .setEventCallback(playerState -> {
                    final Track track = playerState.track;
                    if (track != null) {
                        Log.d("MainActivity", track.name + " by " + track.artist.name);
                    }
                });
    }
}