Android Media player wont work with checkbox?

允我心安 提交于 2019-12-12 01:26:09

问题


I have a song playing in the background, and on the next page is a check box. When it's checked I want the music to stay on and it when it's unchecked I want it to stay off. It works fine except for one way. When I uncheck the music while playing it stops the music as it should. now if I restart the app the music doesnt turn on which is good as well, but when I go to check music it doesnt turn back on until I go back to the previous page. i want to to start once it's rechecked. If the music is playing and I uncheck it, it pauses, and if I check it it starts t back up so I am confused.

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPlayer = MediaPlayer.create(MainActivity.this, R.raw.roy);
        mPlayer.setLooping(true);
        loadPrefs()
    }

    @Override
    public void onDestroy() {
        mPlayer.stop();
        super.onDestroy();
    }

    private void loadPrefs() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean cbValue = sp.getBoolean("CHECKBOX",true);

        if(cbValue) {
            mPlayer.start();
        } else {
            // nothing to do
        }
    }
}

//------------------------------------------

public class next extends Activity {
    CheckBox checkBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.border);
        checkBox = (CheckBox) findViewById(R.id.checkBox1); 
        loadPrefs();
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePrefs("CHECKBOX",checkBox.isChecked());
                loadPrefs();
            }
        }); 
    }

    private void loadPrefs() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean cbValue = sp.getBoolean("CHECKBOX",true);

        if(cbValue) {
            checkBox.setChecked(true);
            MainActivity.mPlayer.start();
        } else {
            checkBox.setChecked(false);
            MainActivity.mPlayer.pause();
        }
    }

    private void savePrefs(String key, Boolean value) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        Editor edit = sp.edit();
        edit.putBoolean(key, value);
        edit.commit();
    }
}

回答1:


I'm not sure about two activities, but could give siggestion in case of usage of single one. The main idea here - store not only state play / pause, but store current playing position also and on resume - just seek to it.

NOTE: In case if You want background play, then your way is completely wrong and You need to rework it using suggestions from "Using a Service with MediaPlayer" (I'm not going to cover it here, because it's completely different and well explained in the documentation).

I would suggest to try the following code (it works fine for me):

public class MyActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
    /** To play music */
    private MediaPlayer mPlayer = null;
    /** To start / pause music */
    private CheckBox mSwitch = null;
    /** To store paused state */
    private boolean mIsPlayerPaused = false;

    /** Key to store state of checkbox */
    private static final String CHECKBOX_KEY = "com.example.TestApp.CHECKBOX_KEY";
    /** Key to store current play position */
    private static final String PLAY_POSITION_KEY = "com.example.TestApp.PLAY_POSITION_KEY";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Show the layout with the test view
        setContentView(R.layout.main);

        mSwitch = (CheckBox) findViewById(R.id.checkBox);
    }

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

        saveState();

        if (mPlayer.isPlaying() || mIsPlayerPaused) {
            mPlayer.stop();
        }

        mPlayer.release();
        mPlayer = null;

        mSwitch.setOnCheckedChangeListener(null);
    }

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

        mPlayer = MediaPlayer.create(this, R.raw.roy);
        mPlayer.setLooping(true);

        loadPrefs();
        mSwitch.setOnCheckedChangeListener(this);
    }

    /**
     * Loads preferences. Should be called before set listener to CheckBox.
     */
    private void loadPrefs() {
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        // get played position
        final int position = sp.getInt(PLAY_POSITION_KEY, 0);

        if (position > 0) {
            mPlayer.seekTo(position);
        }

        final boolean cbValue = sp.getBoolean(CHECKBOX_KEY, false);

        if (cbValue) {
            mPlayer.start();
            mSwitch.setChecked(true);
        } else {
            mIsPlayerPaused = true;
        }
    }

    @Override
    public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
        if (isChecked) {
            if (!mPlayer.isPlaying()) {
                mPlayer.start();
            }
        } else {
            mPlayer.pause();
            mIsPlayerPaused = true;
        }
    }

    /**
     * Saves current playback state.
     */
    private void saveState() {
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        final SharedPreferences.Editor edit = sp.edit();

        edit.putBoolean(CHECKBOX_KEY, mSwitch.isChecked());

        if (mPlayer != null && (mPlayer.isPlaying() || mIsPlayerPaused)) {
            edit.putInt(PLAY_POSITION_KEY, mPlayer.getCurrentPosition());
        } else {
            edit.putInt(PLAY_POSITION_KEY, 0);
        }

        edit.commit();
    }
}


来源:https://stackoverflow.com/questions/17689408/android-media-player-wont-work-with-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!