Search code examples
androidaudioandroid-audiomanager

Android, Allow user to select audio profile and save that choice for later use


The tutorials I see is allowing user to activate audio/sound profile by clicking the button immediately, i dont want to active selected profile immediately, i want to save user's choice for sound profile and activate that choice later with respect to some event, how can i do that, also suggest some good source to learn audio related things in android. I also want to do same treatment for ringer, message and notification volumes


Solution

  • You can use Android preferences to save the user's choices for later use:

    //save prefs
    public void savePrefs(String key, Boolean value){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }
    
    //get prefs
    private String loadPreferences(String key, Boolean value){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String data = sharedPreferences.getBoolean(key, value);
        return data;
    }
    

    If the user clicks audio button, set audioChoice = true in your code. Then save audioChoice into preferences:

    private boolean audioChoice = false;
    
    audioChoice = savePrefs("Choice", audioChoice);
    

    If you want to retrieve audioChoice at a later time, do this:

    audioChoice = loadPreferences("Choice", audioChoice);
    

    If you want more information, here is the android documentation on using SharedPreferences: http://developer.android.com/guide/topics/data/data-storage.html#pref