Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
tools:context=".MainActivity">
<Button
android:id="@+id/spotify_login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/rounded_corners"
android:drawablePadding="8dp"
android:drawableStart="@drawable/spotify_icon"
android:drawableLeft="@drawable/spotify_icon"
android:padding="8dp"
android:text="Log in with Spotify"
android:textAllCaps="false"
android:textColor="@android:color/white" />
</RelativeLayout>
dependencies {
//..other dependencies
implementation 'com.spotify.android:auth:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
}
private var spotifyAccessToken: String? = null
private var spotifyAccessCode: String? = null
private var mCall: Call? = null
private val mOkHttpClient = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
spotify_login_btn.setOnClickListener {
val request = getAuthenticationRequest(AuthenticationResponse.Type.TOKEN)
AuthenticationClient.openLoginActivity(
this,
SpotifyConstants.AUTH_TOKEN_REQUEST_CODE,
request
)
}
}
private fun getAuthenticationRequest(type: AuthenticationResponse.Type): AuthenticationRequest {
return AuthenticationRequest.Builder(
SpotifyConstants.CLIENT_ID,
type,
SpotifyConstants.REDIRECT_URI
)
.setShowDialog(false)
.setScopes(arrayOf("user-read-email"))
.build()
}
override fun onDestroy() {
cancelCall()
super.onDestroy()
}
private fun cancelCall() {
if (mCall != null) {
mCall!!.cancel()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (SpotifyConstants.AUTH_TOKEN_REQUEST_CODE == requestCode) {
val response = AuthenticationClient.getResponse(resultCode, data)
spotifyAccessToken = response.accessToken
fetchSpotifyUserProfile()
}
}
private fun fetchSpotifyUserProfile() {
Log.d("Status: ", "Please Wait...")
if (spotifyAccessToken == null) {
Log.i("Status: ", "Something went wrong - No Access Token found")
return
}
val request = Request.Builder()
.url("https://api.spotify.com/v1/me")
.addHeader("Authorization", "Bearer " + spotifyAccessToken!!)
.build()
cancelCall()
mCall = mOkHttpClient.newCall(request)
mCall!!.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.d("Status: ", "Failed to fetch data: $e")
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: okhttp3.Response) {
try {
val jsonObject = JSONObject(response.body!!.string())
val spotifyId = jsonObject.getString("id")
Log.d("Spotify Id :", spotifyId)
val spotifyDisplayName = jsonObject.getString("display_name")
Log.d("Spotify Display Name :", spotifyDisplayName)
val spotifyEmail = jsonObject.getString("email")
Log.d("Spotify Email :", spotifyEmail)
val spotifyProfilePic = jsonObject.getJSONArray("images")
//Check if user has Avatar
var spotifyPicURL = ""
if (spotifyProfilePic.length() > 0) {
spotifyPicURL = spotifyProfilePic.getJSONObject(0).getString("url")
Log.d("Spotify Avatar :", spotifyPicURL)
}
val accessToken = spotifyAccessToken
Log.d("Spotify AccessToken :", accessToken ?: "")
Log.d("Status: ", "Success get all JSON ${jsonObject.toString(3)}")
} catch (e: JSONException) {
Log.d("Status: ", "Failed to parse data: $e")
}
}
})
}
object SpotifyConstants {
val CLIENT_ID = "MY_CLIENT_ID"
val AUTH_TOKEN_REQUEST_CODE = 0x10
val AUTH_CODE_REQUEST_CODE = 0x11
val REDIRECT_URI = "MY_REDIRECT_URI"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.