java – Test if Spotify is paused using the Android SDK, and store that in a variable accessible from everywhere?

I have a beginner’s understanding of C++ and have no prior experience with Java. I’ve been following https://developer.spotify.com/documentation/android/quick-start/ and started coding an app to control Spotify playback. The issue I’m running into is that I can’t figure out how to create a boolean variable that simply sets itself to true or false based on whether Spotify is playing or not.

The other part that’s getting me stuck is I can’t figure out how to make a variable accessible from everywhere. This is more a problem with my incomplete understanding of Java than anything Spotify-related. I know theres no such thing as a truly global variable in Java, but I’ve tried creating a public global class to hold the “global” variable but it isn’t working right.

I’ve tried using getPlayerState(), isPaused() from playerState(), Subscription<PlayerState> subscribeToPlayerState(), and nothing is working for me. All I want is to be able to run code that evaluates and runs if(paused), do X. I know it’d probably be possible to make a separate boolean that just gets manually updated by my app every time it detects a Spotify change, but that error-prone. I’ve successfully made buttons that pause and unpause, but those buttons only pause and unpause. Spotify has no built-in “toggle play/pause” method, so it’s difficult to make a single button that toggles to and from both states.

Specific answers would be helpful, as well as general guidance like “dude you’re doing X completely wrong” and “you should be doing Y, not Z”. Thank you!

MainActivity.java

    //public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
//    public class Global {
//        public boolean playing;
//    }
    private static final String CLIENT_ID = "3106237a618e4d3386ba107558890270";
    private static final String REDIRECT_URI = "http://localhost:7777/callback";
    private SpotifyAppRemote mSpotifyAppRemote;
    static boolean status;
    //@SerializedName(value="is_paused")
    //public final boolean isPaused;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
//    BroadcastReceiver br = new MyBroadcastReceiver();
//    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
//filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
//this.registerReceiver(br, filter);


    @Override
    protected void onStart() {
        super.onStart();
        ////   Set the connection parameters
        ConnectionParams connectionParams =
                new ConnectionParams.Builder(CLIENT_ID)
                        .setRedirectUri(REDIRECT_URI)
                        .showAuthView(true)
                        .build();
        SpotifyAppRemote.connect(this, connectionParams,
                new Connector.ConnectionListener() {

                    @Override
                    public void onConnected(SpotifyAppRemote spotifyAppRemote) {
                        mSpotifyAppRemote = spotifyAppRemote;
                        Log.d("MainActivity", "Connected! Yay!");

                        // Now you can start interacting with App Remote
                        connected();
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        Log.e("MainActivity", throwable.getMessage(), throwable);

                        // Something went wrong when attempting to connect! Handle errors here
                    }
                });


        // We will start writing our code here.
    }
//    static boolean playing;
//    public class PlayerState extends java.lang.Object(){
//        //@SerializedName(value="is_paused")
//        //public final boolean isPaused;
//    }

    private void connected() {
        // Subscribe to PlayerState
        mSpotifyAppRemote.getPlayerApi()
                .subscribeToPlayerState()
                .setEventCallback(playerState -> {
                    final Track track = playerState.track;
                    if (track != null) {
                        mSpotifyAppRemote.getConnectApi().connectDecreaseVolume();
                        Log.d("MainActivity", track.name + " by " + track.artist.name);
                    }
                });



        // Then we will write some more code here.

        //mSpotifyAppRemote.getPlayerApi().play("spotify:playlist:37i9dQZF1DX2sUQwD7tbmL");
    }

    @Override
    protected void onStop() {
        super.onStop();

        SpotifyAppRemote.disconnect(mSpotifyAppRemote);
        // Aaand we will finish off here.
    }

    public void pauseSpotify(View view) {
        //if(spotifyReceiver.class.)
        mSpotifyAppRemote.getPlayerApi().pause();
    }
    public void resumeSpotify(View view) {
        mSpotifyAppRemote.getPlayerApi().resume();
    }
    //Intent skip = new Intent(this, skipForward.class);
    public void skipForward(View view) {
//        if (spotifyReceiver(intent.getBooleanExtra()) {
//            mSpotifyAppRemote.getPlayerApi().skipNext();
//        }
        mSpotifyAppRemote.getPlayerApi().skipNext();
    }
    public void skipBack(View view) {
        mSpotifyAppRemote.getPlayerApi().skipPrevious();
    }

}

spotifyReceiver.java

    //public boolean playing;
    static final class BroadcastTypes {
        static final String SPOTIFY_PACKAGE = "com.spotify.music";
        static final String PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged";
        static final String QUEUE_CHANGED = SPOTIFY_PACKAGE + ".queuechanged";
        static final String METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged";
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // This is sent with all broadcasts, regardless of type. The value is taken from
        // System.currentTimeMillis(), which you can compare to in order to determine how
        // old the event is.
        long timeSentInMs = intent.getLongExtra("timeSent", 0L);

        String action = intent.getAction();

        if (action.equals(BroadcastTypes.METADATA_CHANGED)) {
            String trackId = intent.getStringExtra("id");
            String artistName = intent.getStringExtra("artist");
            String albumName = intent.getStringExtra("album");
            String trackName = intent.getStringExtra("track");
            int trackLengthInSec = intent.getIntExtra("length", 0);
            // Do something with extracted information...
        } else if (action.equals(BroadcastTypes.PLAYBACK_STATE_CHANGED)) {
            boolean playing = intent.getBooleanExtra("playing", false);
            //playing = intent.getBooleanExtra("playing", false);


            int positionInMs = intent.getIntExtra("playbackPosition", 0);
            // Do something with extracted information
        } else if (action.equals(BroadcastTypes.QUEUE_CHANGED)) {
            // Sent only as a notification, your app may want to respond accordingly.
        }
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lightningtow.pauser2">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Pauser2">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name="spotifyReceiver"
            android:enabled="true"
            android:exported="true">

            <intent-filter>
                <action android:name="com.spotify.music.playbackstatechanged"/>
                <action android:name="com.spotify.music.metadatachanged"/>
                <action android:name="com.spotify.music.queuechanged"/>
            </intent-filter>

        </receiver>
    </application>


</manifest>

Leave a Comment