Android Spotify SDK Implementation & Search Songs Using Spotify API

Android Spotify SDK Implementation & Search Songs Using Spotify API
Here, I will show how to implement Spotify SDK in an Android application and by using the Spotify API, we will see one demo for search songs.

Spotify Android SDK

Spotify Android SDK runs in the background as a service and allows our application to interact with the Spotify app. It will help us get metadata of currently playing songs and using SDK to send basic playback commands.

Here we have two libraries: Spotify Authentication Library and Spotify App Remote Library.

Spotify Authentication Library: Using this library, we can authenticate and get access to Spotify API.
Spotify App Remote Library: This library contains classes for playback control and metadata access.

Follow the steps to implement Spotify SDK:

Step 1:

Create an app in Android studio.

Step 2:

To implement Spotify SDK in our application first, we need to create a project on the Spotify dashboard. We have to register an app on the Spotify dashboard using the given steps here. While registering an application, we need to add a package name and fingerprints for our application. Make sure you add fingerprints for debug and release variants; otherwise, the application will not work. Use commands to get the fingerprints for both variants.

Requirements: Minimum Android SDK version 14, gson ( version 2.6.1) and make sure you have installed the Spotify app on your device.

Step 3:

Download SDK from git repository; here, you will get .aar files for both the libraries.
Add downloaded libraries into the Android studio for our application.

Step 4:

Add below dependencies in build.gradle file

dependencies {

    // your app dependencies

implementation "com.google.code.gson:gson:2.8.5"

implementation 'com.github.kaaes:spotify-web-api-android:0.4.1'

implementation "com.spotify.android:auth:1.2.3"

implementation project(':spotify-app-remote-release-0.7.1')

implementation project(':spotify-auth-release-1.2.3')

}

Step 5:

Create an activity for Spotify login to our application.

public class SpotifyLoginActivity extends AppCompatActivity {

   private static final String TAG = "Spotify " + SpotifyLoginActivity.class.getSimpleName();

   private static final int REQUEST_CODE = 1337;

   public static final String AUTH_TOKEN = "AUTH_TOKEN";

   @Override

   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

setContentView(R.layout.activity_spotify_login);Button mLoginButton = (Button)findViewById(R.id.login_button);

       mLoginButton.setOnClickListener(mListener);

   }

   private void openLoginWindow() {

       AuthorizationRequest.Builder builder = new AuthorizationRequest.Builder(CLIENT_ID, TOKEN,REDIRECT_URL);

       builder.setScopes(new String[]{ "streaming"});

       AuthorizationRequest request = builder.build();

       AuthorizationClient.openLoginActivity(this,REQUEST_CODE,request);

   }

   @Override

   protected void onActivityResult(int requestCode, final int resultCode, Intent data) {

       super.onActivityResult(requestCode, resultCode, data);

       if(requestCode == REQUEST_CODE)

       {

           final AuthorizationResponse response = AuthorizationClient.getResponse(resultCode, data);

           switch (response.getType()) {

               // Response was successful and contains auth token

               case TOKEN:

                   Log.e(TAG,"Auth token: " + response.getAccessToken());

                   Intent intent = new Intent(SpotifyLoginActivity.this,

                           SearchSongsActivity.class);

                   intent.putExtra(AUTH_TOKEN, response.getAccessToken());

                   startActivity(intent);

                   destroy();

                   break;

               // Auth flow returned an error

               case ERROR:

                   Log.e(TAG,"Auth error: " + response.getError());

                   break;

               // Most likely auth flow was cancelled

               default:

                   Log.d(TAG,"Auth result: " + response.getType());

           }

       }

   }


   View.OnClickListener mListener = new View.OnClickListener(){

       @Override

       public void onClick(View view) {

           switch (view.getId()){

               case R.id.login_button:

                   openLoginWindow();

                   break;

           }

       }

   };

   public void destroy(){

       SpotifyLoginActivity.this.finish();

   }

}

Spotify login screen :

Spotify_login_screen

On click of login, it will redirect the Spotify login screen using the Spotify account we need to authenticate our application access.

Step 6:

After login authentication is done, we will create a search song activity.

public class SearchSongsActivity extends AppCompatActivity {

   private String AUTH_TOKEN;

   public static SpotifyService spotifyService;

   private boolean isSingleLight;

   int position;

   @Override

   protected void onCreate(@Nullable Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_search_song);

       AUTH_TOKEN = getIntent().getStringExtra(SpotifyLoginActivity.AUTH_TOKEN);

       setServiceAPI();

       Fragment mFragment = null;

       mFragment = new SearchFragment();

       FragmentManager fragmentManager = getSupportFragmentManager();

       fragmentManager.beginTransaction()

               .replace(R.id.fragment_container, mFragment).commit();

   }

   private void setServiceAPI(){

       Log.d("PlayMusic", "Setting Spotify API Service");

       SpotifyApi api = new SpotifyApi();

       api.setAccessToken(AUTH_TOKEN);

       spotifyService = api.getService();

   }

}

Add one listener class like below:

public class SearchPager {

   private static SearchPager searchPager;

   private SpotifyService spotifyService = SearchSongsActivity.spotifyService;

   public interface CompleteListener {

       void onComplete(List<Track> items);

       void onError(Throwable error);

   }

public static SearchPager getInstance(Context context){

   if(searchPager == null){

       searchPager = new SearchPager();

   }

   return searchPager;

}

public void getTracksFromSearch(String query, CompleteListener listener){

   getData(query, listener);

}

private void getData(String query, final CompleteListener listener){

   spotifyService.searchTracks(query, new SpotifyCallback<TracksPager>() {

       @Override

       public void failure(SpotifyError spotifyError) {

           listener.onError(spotifyError);

       }

       @Override

       public void success(TracksPager tracksPager, Response response) {

           listener.onComplete(tracksPager.tracks.items);

       }

   });

}

}

Spotify search fragment class:

public class SearchFragment extends Fragment {

   private static final String TAG = "Spotify SearchFragment";

   private TextView textViewSearch;

   private EditText editTextSearch;

   private ScalingLayout scalingLayout;

   private SearchPager.CompleteListener mSearchListener;

   private SearchPager mSearchPager;

   public static final String DETAIL_MUSIC = "Detail Music";

   @Override

   public void onCreate(@Nullable Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

   }

   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

       // check if the previous state is SearchResultFragment

       final View view = inflater.inflate(R.layout.fragment_search, container, false);

       mSearchPager = SearchPager.getInstance(getContext());

       textViewSearch = view.findViewById(R.id.textViewSearch);

       final LinearLayout searchLayout = view.findViewById(R.id.searchLayout);

       final ImageButton searchButton = view.findViewById(R.id.search_text_button);

       editTextSearch = view.findViewById(R.id.editTextSearch);

       searchButton.setOnClickListener(mListener);

       scalingLayout = view.findViewById(R.id.scalingLayout);

       scalingLayout.setListener(new ScalingLayoutListener() {

           @Override

           public void onCollapsed() {

               ViewCompat.animate(textViewSearch).alpha(1).setDuration(150).start();

               ViewCompat.animate(searchLayout).alpha(0).setDuration(150).setListener(new ViewPropertyAnimatorListener() {

                   @Override

                   public void onAnimationStart(View view) {

                       textViewSearch.setVisibility(View.VISIBLE);

                   }

                   @Override

                   public void onAnimationEnd(View view) {

                       searchLayout.setVisibility(View.INVISIBLE);

                   }

                   @Override

                   public void onAnimationCancel(View view) {

                   }

               }).start();

           }

           @Override

           public void onExpanded() {

               ViewCompat.animate(textViewSearch).alpha(0).setDuration(200).start();

               ViewCompat.animate(searchLayout).alpha(1).setDuration(200).setListener(new ViewPropertyAnimatorListener() {

                   @Override

                   public void onAnimationStart(View view) {

                       searchLayout.setVisibility(View.VISIBLE);

                   }

                   @Override

                   public void onAnimationEnd(View view) {

                       textViewSearch.setVisibility(View.INVISIBLE);

                   }

                   @Override

                   public void onAnimationCancel(View view) {

                   }

               }).start();

           }

           @Override

           public void onProgress(float progress) {

           }

       });

       scalingLayout.setOnClickListener(new View.OnClickListener() {

           @Override

           public void onClick(View view) {

               if (scalingLayout.getState() == State.COLLAPSED) {

                   scalingLayout.expand();

               }

           }

       });

       view.findViewById(R.id.rootLayout).setOnClickListener(new View.OnClickListener() {

           @Override

           public void onClick(View view) {

               if (scalingLayout.getState() == State.EXPANDED) {

                   scalingLayout.collapse();

                   if(editTextSearch.getText().toString().equals(""))

                       textViewSearch.setText("Search");

               }

           }

       });

       return view;

   }

   View.OnClickListener mListener = new View.OnClickListener() {

       @Override

       public void onClick(View view) {

           switch (view.getId()){

               case R.id.search_text_button:

                   String query = editTextSearch.getText().toString();

                   Log.d(TAG, "Query: " + query);

                   scalingLayout.collapse();

                   if(query.equals("")){

                       textViewSearch.setText("Search");

                   } else {

                       Log.e("Data","callSearchResult");

                       queryData(query);

                       textViewSearch.setText(query);

                   }

                   break;

           }

       }

   };

   private void queryData(String query){

       mSearchListener = new SearchPager.CompleteListener() {

           @Override

           public void onComplete(List<Track> items) {

               listManager.clearList();

               for(Track track : items){

                   Music music = new Music(

                           track.id,

                           track.uri,

                           track.name,

                           track.album.name,

                           track.album.images.get(0).url,

                           track.duration_ms,

                           track.artists.get(0).name,

                           track.artists.get(0).id

                   );

                   listManager.addTrack(music);

               }

               Log.d(TAG, "query finished! Updating view...");

              getSongList();

           }

           @Override

           public void onError(Throwable error) {

               Log.d(TAG, error.getMessage());

           }

       };

       mSearchPager.getTracksFromSearch(query, mSearchListener);

   }

   private void getSongList(){

       List<Music> mList = listManager.getTrackLists();

       Log.e("ListSongs",""+mList.toString())

   }

   }

Search fragment fragment_search.xml file :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

   xmlns:app="http://schemas.android.com/apk/res-auto"

   android:orientation="vertical"

   android:id="@+id/rootLayout"

   android:background="@color/colorPrimaryDark"

   android:layout_width="match_parent"

   android:layout_height="match_parent">

   <iammert.com.view.scalinglib.ScalingLayout

       android:id="@+id/scalingLayout"

       android:layout_width="match_parent"

       android:layout_height="38dp"

       android:layout_marginBottom="8dp"

       android:layout_marginLeft="16dp"

       android:layout_marginRight="16dp"

       android:layout_marginTop="8dp"

       app:radiusFactor="0.2">

       <RelativeLayout

           android:layout_width="match_parent"

           android:layout_height="match_parent"

           android:background="@color/colorGrayLight">

           <LinearLayout

               android:id="@+id/searchLayout"

               android:layout_width="match_parent"

               android:layout_height="match_parent"

               android:gravity="center_vertical"

               android:orientation="horizontal"

               android:layout_marginLeft="16dp"

               android:layout_centerVertical="true"

               android:visibility="invisible">

               <EditText

                   android:id="@+id/editTextSearch"

                   android:layout_width="match_parent"

                   android:layout_height="match_parent"

                   android:layout_weight="1"

                   android:background="@null"

                   android:textColor="#ffffff"/>

               <ImageButton

                   android:id="@+id/search_text_button"

                   android:layout_width="match_parent"

                   android:layout_height="wrap_content"

                   android:layout_weight="8"

                   android:background="@drawable/ic_search_black_24dp" />

           </LinearLayout>

           <TextView

               android:id="@+id/textViewSearch"

               android:layout_width="wrap_content"

               android:layout_height="wrap_content"

               android:hint="Search"

               android:textSize="12sp"

               android:textColorHint="#ffffff"

               android:layout_centerInParent="true"

               android:textColor="#ffffff"

               android:textStyle="bold" />

       </RelativeLayout>

   </iammert.com.view.scalinglib.ScalingLayout>

</LinearLayout>

In the getSongList method on the search Fragment, we will get the searched song list we will use as per our use.

Note: Android Spotify SDK is currently a beta release, its functionality may be changed if you face some issues; check with official documentation here.

Hope it will be helpful to you!!!😊

Priyanka

Android Developer

Priyanka is an android developer with around 3.5 years of experience developing Android applications with core functionality. She has in-depth knowledge of Java and React Native. Priyanka likes to learn new things and share.

The founder's survey report on "What Matters For Startup" is released - Get your copy and learn the trends of successful companies :)

Download Free eBook Now!

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

"Mindbowser was very helpful with explaining the development process and started quickly on the project."

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

"The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs."

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

"They're very tech-savvy, yet humble."

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

"Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier"

author
Katie Taylor
Founder, Child Life On Call
coma

“As a founder of a budding start up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity."

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give