Application Lifecycle Beta
When an application connects to Spotify client through the SpotifyAppRemote API, it will prevent Spotify from shutting down even if the user is not playing anything. This is expected behavior - we want Spotify to remain active as long as there's something interacting with it. At the same time the application using the Spotify App Remote SDK should not keep Spotify alive if there's no need for it, for example if it's in the background. The Spotify client will take care of the background playback which means you don't need to do it. In most cases you don't need to implement your own service to keep the connection alive, it's enough to connect when user is actually interacting with your app and disconnect when they're not.
We recommend connecting to Spotify in the onStart method of the Activity that shows the playback state and controls, and disconnecting in the onStop method. Do not keep the connection alive when your app is in the background, otherwise Spotify will not be able to shutdown when it's inactive. We also recommend that your app checks for an existing connection before connecting again - otherwise two connections will be created and this will keep Spotify running in the background until the app is killed.
_12@Override_12protected void onStart() {_12 super.onStart();_12 SpotifyAppRemote.disconnect(mSpotifyAppRemote);_12 SpotifyAppRemote.connect(this, mConnectionParams, mConnectionListener);_12}_12_12@Override_12protected void onStop() {_12 super.onStop();_12 SpotifyAppRemote.disconnect(mSpotifyAppRemote);_12}
If the connection succeeds, you're good to go! If it fails then you can use connection errors to show additional visual feedback to the user. For details about connection errors see the error handling page.
Specifically, for cases where the user is not logged in to Spotify, or the user has not authorized your app, you can use the Authorization Library to prompt them to log in and approve the required scopes.
_29Connector.ConnectionListener mConnectionListener = new Connector.ConnectionListener() {_29 @Override_29 public void onConnected(SpotifyAppRemote spotifyAppRemote) {_29 mSpotifyAppRemote = spotifyAppRemote;_29 // setup all the things_29 }_29_29 @Override_29 public void onFailure(Throwable error) {_29 if (error instanceof NotLoggedInException || error instanceof UserNotAuthorizedException) {_29 // Show login button and trigger the login flow from auth library when clicked_29 } else if (error instanceof CouldNotFindSpotifyApp) {_29 // Show button to download Spotify_29 }_29 }_29};_29_29@Override_29protected void onStart() {_29 super.onStart();_29 SpotifyAppRemote.disconnect(mSpotifyAppRemote);_29 SpotifyAppRemote.connect(this, mConnectionParams, mConnectionListener);_29}_29_29@Override_29protected void onStop() {_29 super.onStop();_29 SpotifyAppRemote.disconnect(mSpotifyAppRemote);_29}