Note: The Android SDK is currently a beta release; its content and functionality is likely to change significantly without warning. By using the Spotify Developer Tools, you accept our Developer Terms of Service.

In this guide, we’re going to create your first application with the Spotify Android SDK. You’ll be able to play a track in your Android application by the end of it.

Creating a Simple App

To create this application, you’ll need the following:

We won’t go into too much detail about Android app development in the Quick Start guide. Our aim is to make it easy to setup your environment and ensure you can connect to the Spotify service to play an audio track.

Register Your App

You’ll need to register your application with Spotify. It’s free and you can do it through our Developer Dashboard. [Take a look at this guide][register-your-app] for more information.

Create the App

Create a New Project

  1. Open Android Studio and create a New Project:
    • Application name: SimpleApp
    • Company domain: companydomain.applicationname
    • Include C++ support: ✕ No
    • Include Kotlin support: ✕ No
  2. You should see the Target Android Devices screen.
    • Select Phone and Tablet with API level 15: Android 4.0.3 (IceCreamSandwich)
    • Include Android Instant App support: ✕ No
  3. When prompted to add an activity to Mobile, select Empty Activity.
  4. Fill in the following details:
    • Activity Name: MainActivity
    • Generate Layout File: ✓ Yes
    • Layout Name: activity_main
    • Backwards Compatibility (AppCompat): ✕ No

    Note: These values are required later in the code examples. If you enter other values, be sure to modify the code accordingly.

  5. Click Finish.
  6. Install Dependencies:
    • Go to Tools > Android > SDK Manager > SDK Tools
    • Install the Android SDK Build-Tools dependency. If you receive an error, ignore it for the time being.

    Note for Windows Users: If a security alert appears, click Allow Access; Android Studio creates your project. If Android Studio fails to create the project, look in the Messages tab at the bottom of the screen.

Install the Android SDK

In order to install the Spotify Android SDK (which is made up of the Authentication & Player SDKs), you can either run them as a command or manually:

Install via Terminal

# Your Android SimpleApp folder.
$ cd ~/AndroidStudioProjects/SimpleApp

# Download and unpack the Spotify Android Player SDK.
$ wget https://github.com/spotify/android-sdk/archive/24-noconnect-2.20b.zip
$ unzip 24-noconnect-2.20b.zip
$ mv android-sdk-24-noconnect-2.20b/spotify-player-24-noconnect-2.20b.aar .
$ rm -rf android-sdk-24-noconnect-2.20b/ 24-noconnect-2.20b.zip
$ mv spotify-player-24-noconnect-2.20b.aar app/libs/

# Download and unpack the Spotify Authentication Player SDK.
$ wget https://github.com/spotify/android-auth/archive/1.0.zip
$ unzip 1.0.zip
$ rm -rf 1.0.zip



Install manually

  1. Download both the Auth/Player Android SDKs in ZIP form:
  2. In a file explorer, do the following:
    • Navigate to the folder your SimpleApp lives in. You usually set this when you created the project in Android Studio
    • Inside this folder, navigate to app/libs
    • Unzip both ZIP files you downloaded in Step 1
    • Move the android-auth-1.0 folder to the app/libs folder you just opened.
    • Move the spotify-player-24-noconnect-2.20b.aar folder to the same app/libs folder.

Update Android configuration

  1. In Android Studio, do the following:
    • Open Gradle Scripts
    • Open build.gradle with Module: app
  2. Change the contents of the build.gradle to the following:
     apply plugin: 'com.android.application'
    
     android {
         compileSdkVersion 26
         buildToolsVersion '26.0.1'
         defaultConfig {
             applicationId "companydomain.applicationname.simpleapp"
             minSdkVersion 15
             targetSdkVersion 26
             versionCode 1
             versionName "1.0"
         }
         buildTypes {
             release {
                 minifyEnabled false
                 proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
             }
         }
     }
    
     repositories {
         mavenCentral()
         flatDir {
             dirs 'libs'
         }
     }
    
     dependencies {
         compile fileTree(include: ['*.jar'], dir: 'libs')
         compile 'com.android.support.constraint:constraint-layout:1.0.2'
    
         // This library handles authentication and authorization
         compile 'com.spotify.android:auth:1.0.0-alpha'
    
         // This library handles music playback
         compile 'com.spotify.sdk:spotify-player-24-noconnect-2.20b@aar'
     }
    

    In order for your code to resolve dependencies properly:

    • The buildToolsVersion, applicationId and the aar file version must match your installation.
    • You need to add the flatDir entry to the repositories section as seen the code above.

    Note: In the second “compile” line in the code above, the Gradle file dependency is identified by using a colon in place of the first dash of the aar file name. The colon is actually a separator between the parts of the dependency. For further information about Gradle dependency syntax, see: Grade Dependency Management.

  3. In Android Studio, from the Tools menu, select Android, and then select Sync Project with Gradle Files; you should now have no error messages in the messages pane.

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 (no password):
    # On Bash style shells:
    $ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v | grep SHA1
    
    # On Windows Powershell
    $ keytool -exportcert -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. 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 -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEYSTORE_PATH> -list -v | grep SHA1
    
    # On Windows Powershell:
    $ keytool -exportcert -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.

Write the App Code

  • In a text editor: Open the /app/src/main/java/applicationname/companyname/simpleapp/MainActivity.java file.
  • In Android Studio: Open the MainActivity class inside of your editor.

When you have found the MainActivity code, replace its entire contents with below:

package applicationname.companyname.simpleapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.spotify.sdk.android.authentication.AuthenticationClient;
import com.spotify.sdk.android.authentication.AuthenticationRequest;
import com.spotify.sdk.android.authentication.AuthenticationResponse;
import com.spotify.sdk.android.player.Config;
import com.spotify.sdk.android.player.ConnectionStateCallback;
import com.spotify.sdk.android.player.Error;
import com.spotify.sdk.android.player.Player;
import com.spotify.sdk.android.player.PlayerEvent;
import com.spotify.sdk.android.player.Spotify;
import com.spotify.sdk.android.player.SpotifyPlayer;

public class MainActivity extends Activity implements
        SpotifyPlayer.NotificationCallback, ConnectionStateCallback
{
    // TODO: Replace with your client ID
    private static final String CLIENT_ID = "yourclientid";

    // TODO: Replace with your redirect URI
    private static final String REDIRECT_URI = "yourcustomprotocol://callback";

    private Player mPlayer;

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPlaybackEvent(PlayerEvent playerEvent) {
        Log.d("MainActivity", "Playback event received: " + playerEvent.name());
        switch (playerEvent) {
            // Handle event type as necessary
            default:
                break;
        }
    }

    @Override
    public void onPlaybackError(Error error) {
        Log.d("MainActivity", "Playback error received: " + error.name());
        switch (error) {
            // Handle error type as necessary
            default:
                break;
        }
    }

    @Override
    public void onLoggedIn() {
        Log.d("MainActivity", "User logged in");
    }

    @Override
    public void onLoggedOut() {
        Log.d("MainActivity", "User logged out");
    }

    @Override
    public void onLoginFailed(Error var1) {
        Log.d("MainActivity", "Login failed");
    }

    @Override
    public void onTemporaryError() {
        Log.d("MainActivity", "Temporary error occurred");
    }

    @Override
    public void onConnectionMessage(String message) {
        Log.d("MainActivity", "Received connection message: " + message);
    }
}

Make sure you update the values in the code above:

  • The package name on the first line.
  • The CLIENT_ID variable. You can retrieve this the Spotify Developer Dashboard.
  • The REDIRECT_URI that you have assigned for your application.

Authenticate the User

You’re now ready to write the logic that authenticates your user with Spotify. This will be done through a modal inside of your application that embeds https://accounts.spotify.com for OAuth authentication.

Inside of your code, you can write the logic to instantiate an authentication between your user and Spotify. This logic lives within the onCreate command. You can modify your MainActivity code as you see below.

  // Request code that will be used to verify if the result comes from correct activity
  // Can be any integer
  private static final int REQUEST_CODE = 1337;

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

      // The only thing that's different is we added the 5 lines below.
      AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(CLIENT_ID, AuthenticationResponse.Type.TOKEN, REDIRECT_URI);
      builder.setScopes(new String[]{"user-read-private", "streaming"});
      AuthenticationRequest request = builder.build();

      AuthenticationClient.openLoginActivity(this, REQUEST_CODE, request);
  }

Notes:

  • The setScopes method defines what scopes your app needs the user to approve. In this example, you just need the user’s details (user-read-private) and to stream music (streaming). Here’s a full list of scopes you can ask for.
  • The Android SDK uses the same authentication and authorization process as the Spotify Web API. For detailed information, see the Web API Authorization.

When this method is executed, the user is asked to login and authorize the application scopes. When the authorization is finished, the result is delivered to the onActivityResult callback. Modify the method as follows:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    // Check if result comes from the correct activity
    // The next 19 lines of the code are what you need to copy & paste! :)
    if (requestCode == REQUEST_CODE) {
        AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
        if (response.getType() == AuthenticationResponse.Type.TOKEN) {
            Config playerConfig = new Config(this, response.getAccessToken(), CLIENT_ID);
            Spotify.getPlayer(playerConfig, this, new SpotifyPlayer.InitializationObserver() {
                @Override
                public void onInitialized(SpotifyPlayer spotifyPlayer) {
                    mPlayer = spotifyPlayer;
                    mPlayer.addConnectionStateCallback(MainActivity.this);
                    mPlayer.addNotificationCallback(MainActivity.this);
                }

                @Override
                public void onError(Throwable throwable) {
                    Log.e("MainActivity", "Could not initialize player: " + throwable.getMessage());
                }
            });
        }
    }
}

In this method, you extract the OAuth access token provided by the callback, and pass it to a Config object that is required when creating the player. You can also get the player by using the Spotify class. For more information, see the SDK API reference of the Spotify class.

@Override
public void onLoggedIn() {
    Log.d("MainActivity", "User logged in");

    // This is the line that plays a song.
    mPlayer.playUri(null, "spotify:track:2TpxZ7JUBn3uw46aR7qd6V", 0, 0);
}

When the player is logged in, ask the player to play the Spotify track. Play the song.

Interact with the Spotify Android Player

Now you have the Spotify object, use it to refer to the player in your code. Here’s a few things you should know:

  • All calls are asynchronous. The player runs in a separate thread from your main app thread, so it’s safe to call player methods from your GUI.
  • There may be a delay in execution. Due to non-blocking requests and our SDK having commands to process on initialisation, there might be an initial small delay.
  • You can now play a song. You’ll need to call mPlayer.playURI with a Spotify URI (Example: spotify:track:...) to play a song. This is what URIs we support.
  • Destroy the player when you’re done. When you don’t need the player, dispose of it using Spotify.destroyPlayer. Typically it is done inside of the onDestroy callback.
      @Override
      protected void onDestroy() {
          Spotify.destroyPlayer(this);
          super.onDestroy();
      }
    

    Important: Failure to run Spotify.destroyPlayer will result in your app leaking resources.

  • Actually, release resources when you’re done with them. The SDK uses native resources, and multiple fragments may each have a reference to the singleton instance of the Player, so it’s important you release resources when you’re done with them.

With this in mind, along with your client ID and redirect URI, the complete MainActivity.java should now look as follows:

// SimpleApp
// Created by Spotify on 02/08/17.
// Copyright (c) 2017 Spotify. All rights reserved.
package applicationname.companyname.simpleapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.spotify.sdk.android.authentication.AuthenticationClient;
import com.spotify.sdk.android.authentication.AuthenticationRequest;
import com.spotify.sdk.android.authentication.AuthenticationResponse;
import com.spotify.sdk.android.player.Config;
import com.spotify.sdk.android.player.ConnectionStateCallback;
import com.spotify.sdk.android.player.Error;
import com.spotify.sdk.android.player.Player;
import com.spotify.sdk.android.player.PlayerEvent;
import com.spotify.sdk.android.player.Spotify;
import com.spotify.sdk.android.player.SpotifyPlayer;

public class MainActivity extends Activity implements
        SpotifyPlayer.NotificationCallback, ConnectionStateCallback
{
    private static final String CLIENT_ID = "yourclientid";
    private static final String REDIRECT_URI = "yourcustomprotocol://callback";
    private Player mPlayer;
    private static final int REQUEST_CODE = 1337;

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

        AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(CLIENT_ID, AuthenticationResponse.Type.TOKEN, REDIRECT_URI);
        builder.setScopes(new String[]{"user-read-private", "streaming"});
        AuthenticationRequest request = builder.build();

        AuthenticationClient.openLoginActivity(this, REQUEST_CODE, request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (requestCode == REQUEST_CODE) {
            AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
            if (response.getType() == AuthenticationResponse.Type.TOKEN) {
                Config playerConfig = new Config(this, response.getAccessToken(), CLIENT_ID);
                Spotify.getPlayer(playerConfig, this, new SpotifyPlayer.InitializationObserver() {
                    @Override
                    public void onInitialized(SpotifyPlayer spotifyPlayer) {
                        mPlayer = spotifyPlayer;
                        mPlayer.addConnectionStateCallback(MainActivity.this);
                        mPlayer.addNotificationCallback(MainActivity.this);
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("MainActivity", "Could not initialize player: " + throwable.getMessage());
                    }
                });
            }
        }
    }

    @Override
    protected void onDestroy() {
        Spotify.destroyPlayer(this);
        super.onDestroy();
    }

    @Override
    public void onPlaybackEvent(PlayerEvent playerEvent) {
        Log.d("MainActivity", "Playback event received: " + playerEvent.name());
        switch (playerEvent) {
            // Handle event type as necessary
            default:
                break;
        }
    }

    @Override
    public void onPlaybackError(Error error) {
        Log.d("MainActivity", "Playback error received: " + error.name());
        switch (error) {
            // Handle error type as necessary
            default:
                break;
        }
    }

    @Override
    public void onLoggedIn() {
        Log.d("MainActivity", "User logged in");

        mPlayer.playUri(null, "spotify:track:2TpxZ7JUBn3uw46aR7qd6V", 0, 0);
    }

    @Override
    public void onLoggedOut() {
        Log.d("MainActivity", "User logged out");
    }

    @Override
    public void onLoginFailed(Error var1) {
        Log.d("MainActivity", "Login failed");
    }

    @Override
    public void onTemporaryError() {
        Log.d("MainActivity", "Temporary error occurred");
    }

    @Override
    public void onConnectionMessage(String message) {
        Log.d("MainActivity", "Received connection message: " + message);
    }
}

Update the App Manifest

You’re almost done! Before you run your application, you’ll need to update your AndroidManifest.xml file with a few things:

  1. Find your AndroidManifest.xml inside of the /app/src/main folder.
  2. Add the following code to the body of <manifest>:
     <uses-permission android:name="android.permission.INTERNET"/>
    
  3. Add the following code to the body of <application>:
     <activity
       android:name="com.spotify.sdk.android.authentication.LoginActivity"
       android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
    
  4. Check the package attribute on the <manifest> tag matches your application domain. Usually found on the 2nd line. In this case, it should be companydomain.applicationname.simpleapp.

With the changes, the updated AndroidManifest.xml should look like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="companydomain.applicationname.simpleapp">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>    
        </activity>
        <activity
            android:name="com.spotify.sdk.android.authentication.LoginActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"/>   
    </application>
</manifest>

Build and Run Your Project

  1. To build and run your app in Android Studio: Run > Run ‘app’ A few things to note:
    • Android Studio may prompt you to a device or an emulator that you want to run the app on.
    • If you cannot get your app to run, see Debugging with Android Studio on the Google Android developer page.
    • As soon as the app starts, it opens the Spotify authorization service login dialog.
  2. Log in with your Spotify Premium account credentials. It won’t work with a free account.
  3. Click the button that allows the app to access the Spotify APIs. When the access token is returned, the app immediately creates a Player object, displays the text “Hello World”, and starts playback of the selected track. If you can hear the dulcet tones of Tania Bowra you have completed the Quick Start guide. Hooray!

Feel free to experiment with the Android SDK beta and to report problems through the public issue tracker on GitHub. We’d love to hear your feedback! Please don’t be afraid to reach out to us.