How to make MediaPlayer backward compatible?

Learn how to make your Android MediaPlayer implementation backward compatible with older versions of Android to ensure a smooth multimedia experience across all devices.
MediaPlayer, Android, backward compatibility, multimedia, Android development

    // Example of backward compatible MediaPlayer setup
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;

    public class MainActivity extends AppCompatActivity {
        private MediaPlayer mediaPlayer;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            // Initialize MediaPlayer
            mediaPlayer = MediaPlayer.create(this, R.raw.sample_audio);

            Button playButton = findViewById(R.id.play_button);
            playButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
                    }
                }
            });

            Button stopButton = findViewById(R.id.stop_button);
            stopButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer.prepareAsync(); // Handle compatibility with async preparation
                    }
                }
            });
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
        }
    }
    

MediaPlayer Android backward compatibility multimedia Android development