How to add Spotify Login button to your Android app using Kotlin
- October 23, 2019
- John Codeos
Today, I’m going to show you have to add a Spotify Login button to your app as a sign in method for your users.
Let’s get started
First, go to developer.spotify.com/dashboard and login with your Spotify account. (You don’t need Spotify Premium to have access to Spotify for Developers.)
Next, create a new app by pressing the box.
In the new window, fill in all the requirement fields, like app name, description e.t.c., and press NEXT.
…next step, choose if it’s a commercial app or not. In this example, the answer is NO.
Check the boxes and press SUBMIT.
Once you get to the dashboard of your app, go to EDIT SETTINGS.
In the new window, add your website (if you have one), as Redirect URIs add the name of your app and at the end add :// , for this example is spotifysigninexample://, and lastly, in Android Packages add your package name and your SHA1 Fingerprint and press SAVE
Creating the Spotify Login Button
First, add a Button to your XML file. In this example, we have a button, with Spotify‘s green color, in the middle of the activity_main.xml.
Create a new Kotlin object file by right-clicking on your app’s package name on the left side and go New > Kotlin File/Class.
Give it the name SpotifyConstants, choose Object and press OK.
Inside the new file, copy and paste the following code and replace the CLIENT_ID and REDIRECT_URI with yours.
Add the following dependencies in your build.gradle(Module: app)
In your Kotlin class of your Activity, MainActivity in this example, add a listener to your button, and create the authentication request.
Here, we use the scopes user-read-email to get the user’s email address.
There’s a list with all the authorization scopes here, if you want to get more info from users.
After the user has completed the authorization, it returns the access token through the onActivityResult function and the app gets the data by making an HTTP request to https://api.spotify.com/v1/me using the OkHttp libray.
Lastly, cancel the HTTP request when the Activity has been destroyed.
That’s it! Done!
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!