Skip to content Skip to sidebar Skip to footer

Can I Insert A Android:defaultValue Trait For RingtonePreference, Via XML?

Is there a way to add a default value in a RingtonePreference, via XML? For example, here's what my preference.xml looks like.

Solution 1:

You can define the default in the XML. As you said, it needs a URI. Simply put the default URI for what you need. For example, for a default alarm sound you would put:

<RingtonePreference android:key="alarm"
android:title="Alarm" android:name="Alarm"
android:summary="Select an alarm"
android:ringtoneType="alarm" android:showDefault="true"
android:defaultValue="content://settings/system/alarm_alert" />

For a notification you would put:

android:defaultValue="content://settings/system/notification_sound"

Etc.


Solution 2:

Figured out a work-around, in setting the default ringtone.

For the people who uses both a RingtonePreference and PreferenceManager.setDefaultValues(), android:defaultValue on a RingtonePreference takes in a string to a ringtone's URI. By providing an empty string, you're defaulting the preference to "silence," while other strings will probably lead to no valid URI.

The work-around, then, is to provide a bogus string, such as android:defaultValue="defaultRingtone":

<RingtonePreference android:key="alarm"
android:title="Alarm" android:name="Alarm"
android:summary="Select an alarm"
android:ringtoneType="alarm" android:showDefault="true"
android:defaultValue="defaultRingtone" />

When calling PreferenceManager.setDefaultValues(), grab the preference, and check if the bogus string is being stored:

// Set the stored preferences to default values defined in options.xml
PreferenceManager.setDefaultValues(this, R.layout.options, false);

// Check the stored string value, under the RingtonPreference tag
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final String savedUri = savedState.getString("alarm", "");

// By default, set the alarm's URI to null
Uri alarmUri = null;

// Check if a String was actually provided
if(savedUri.length() > 0) {

  // If the stored string is the bogus string...
  if(savedUri.equals("defaultRingtone")) {

    // Set the alarm to this system's default alarm.
    alarmUri = Settings.System.DEFAULT_ALARM_ALERT_URI;

    // Save this alarm's string, so that we don't have to go through this again
    final SharedPreferences.Editor saveEditor = saveState.edit();
    saveEditor.putString("alarm", alarmUri.toString());
    saveEditor.commit();
  }

  // Otherwise, retrieve the URI as normal.
  else {
    alarmUri = Uri.parse(savedUri);
  }
}

Post a Comment for "Can I Insert A Android:defaultValue Trait For RingtonePreference, Via XML?"