synthesis
synthesis

Reputation: 95

android: Shared Preferences only for active session (until it will be destroyed)

I've a music service which is steering my music with a checkbox. The checkbox states will be saved in my shared preferences correctly! Basic config = music at app start ON and checkbox ON too. So long all works fine!

I want to save these states ONLY in the active app session. After restarting my app, it should be the basic state (music and checkbox ON). In this code he starts with this state which was the last one.

Thx for ur help!

Java Code:

    chkBoxMusic = (CheckBox) findViewById(R.id.checkBoxMusic);

    boolean isChecked = getBooleanFromPreferences("isChecked");
    chkBoxMusic.setChecked(isChecked);

    chkBoxMusic.setOnCheckedChangeListener(new OnCheckedChangeListener() {
   public void onCheckedChanged(CompoundButton buttonview, boolean isChecked) {

    Log.i("boolean",""+isChecked);
    ActivitySound.this.putBooleanInPreferences(isChecked,"isChecked");

       if (!isChecked) {

          stopService(new Intent(ActivitySound.this, MusicService.class));
       }

       else {

          startService(new Intent(ActivitySound.this, MusicService.class));
       }

      }

       });

   }

    public void putBooleanInPreferences(boolean isChecked,String key) {

    SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, isChecked);
    editor.commit();        
}

    public boolean getBooleanFromPreferences(String key) {

    SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
    Boolean isChecked = sharedPreferences.getBoolean(key, false);

    return isChecked;       

}

Upvotes: 0

Views: 1588

Answers (1)

emrys57
emrys57

Reputation: 6806

To remove all shared preferences:

SharedPreferences myPrefs = getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.clear();
editor.commit();

But exactly when to do that is still under negotiation - see comments above! It's not entirely clear what you want even now. You could try putting this in the onStop method of your Activity and seeing if that gives the results you want.

Upvotes: 1

Related Questions