Search code examples
androidsharedpreferencestogglebuttonaudio-playerandroid-music-player

implement music with SharedPreferences in android


i'm building an app in android, i've three classes right now, one Main, one Music and one Setting. i'm trying to put music in my app, so that when i exit the app it'll stop. i've done that part.

i also have a toggle button in the setting class, which controls the music on/off, and i'm using SharedPreferences for the app to remember if the music is off or on. everything work when i enter the app and stay there, the off state really turn off the music and the on state turn her on, but the problem is when i exit and re-enter the Main class start playing music again. is there a way to check if the toggle button is checked in the Main class? i dont find any...

other problem, how can i mute the music when the phone is in mute state? i looked at switch method in this site but it didnt work. any help will be great!

here are the classes:

Main-

public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Music.play(this, R.raw.pirates);
}

public void setting_onclick(View view) {
       Intent i = new Intent("net.lirazarviv.Setting");
       startActivity(i);
   }

@Override
  protected void onPause() {
    if (this.isFinishing()){ //basically BACK was pressed from this activity
      Music.stoping();

    }
    Context context = getApplicationContext();
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    if (!taskInfo.isEmpty()) {
      ComponentName topActivity = taskInfo.get(0).topActivity; 
      if (!topActivity.getPackageName().equals(context.getPackageName())) {
        Music.stoping();
      }
    }
    super.onPause();
  }
}

Music-

public class Music {
private static MediaPlayer mp = null;

public static void play(Context context, int resource) {
         mp = MediaPlayer.create(context, resource);
         mp.setLooping(true);
         mp.start();
      }

public static void stop(Context context) { 
      if (mp != null) {
         mp.stop();
         mp.pause();
         mp.release();
         mp = null;
      }
   }


public static void playing() {
        mp.start();
}

public static void stoping() {
         mp.pause();

}
}

Setting-

public class Setting extends Activity {
ToggleButton Button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setting);
    addListenerOnButton();
    loadPrefs();
}

public void addListenerOnButton() {

    Button = (ToggleButton) findViewById(R.id.MusicIconSelector);
    Button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                Music.stoping();
                savePrefs("Button",true);
            }
            else { 
                Music.playing();
                savePrefs("Button",false);
            }
        }
    });
}

private void loadPrefs() {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            boolean cbValue = sp.getBoolean("Button", false);
            if(cbValue){
                Button.setChecked(true);
            }else{
                Button.setChecked(false);
            }
        }


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

}


Solution

  • instead of using PreferenceManager.getDefaultSharedPreferences you can use Context.getSharedPreferences. By using this you can read write to same shared preferences from any component. For Eample

    SharedPreferences sp = getSharedPreferences(name, MODE_PRIVATE);
    

    you can access the shared preference by the name from any activity.