搜索曲目 Spotify Android

Searching Tracks Spotify Android

我目前可以使用 Android SDK 播放来自 Spotify 的曲目。我按照此处 https://developer.spotify.com/documentation/android/quick-start/. I would like to allow for a functionality to allow the user to search for a song, as far as I know (correct me if I'm wrong), this is not supported by the Android SDK but is supported by the web API as documented here https://developer.spotify.com/documentation/web-api/reference/search/search/ 的描述进行授权。问题是此请求需要访问令牌。使用来自 SDK 的授权流程时是否可以获取访问令牌,如果可以,如何获取?

你是对的。为了使用 Spotify 的 Web API,您需要一个有效的访问令牌。您链接的指南使用 App Remote SDK 的内置身份验证流程。它在内部请求一个包含 app-remote-control 范围的访问令牌。虽然我实际上在参考中找不到任何允许检索该确切访问令牌的内容。


在这种情况下,您必须使用 Android Auth library. This guide shows two ways of authentication while the first one which uses either the Spotify client or if not installed a WebView fallback is the one they highly recommend. Following this guide at some point you will get a AuthenticationResponse 对象,您可以在其中使用名为 getAccessToken() 的方法来检索访问令牌,稍后您可以在 Spotify 的 Web API 中使用如以下代码片段所示。如前所述,至少包括 app-remote-control 范围很重要。如果您想获取用户特定数据(例如播放列表),您还需要包括相应的范围。

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

  // Check if result comes from the correct activity
  if (requestCode == REQUEST_CODE) {
    AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);

    switch (response.getType()) {
      // Response was successful and contains auth token
      case TOKEN:
        // Handle successful response
        String accessToken = response.getAccessToken();
        break;

      // Auth flow returned an error
      case ERROR:
        // Handle error response
        break;

      // Most likely auth flow was cancelled
      default:
        // Handle other cases
    }
  }
}