2011-04-08

A Preference that get result back from Activity it started

We know that Preferences in Android don't provide public interface to get result back from the activities they launched. The only clue we can find is that RingtonePreference has done the exact thing in protected level. Fortunately, It is very easy to extend RingtonePreference.

So, this is the behavior of RingtonePreference that we want to achieve,
  1. Click to start our activity (not RingtonePicker)
  2. Get result back from activity and store it as SharedPreference for later use. (any kind of result other than Ringtone Uri)
you definitely need to do some modifications on RingtonePreference as I did.

I am developing a ContactPreference in my application that starts an activity for user to pick contacts and returns them back to the ContactPreference. Here is what I did by overriding RingtonePreference,

public class ContactPreference extends android.preference.RingtonePreference {
    // 
    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (super.onActivityResult(requestCode, resultCode, data)) {
            ArrayList addrList =null;
            if (data != null) {    
                addrList = data.getStringArrayListExtra(ContactPicker.EXTRA_ADDRESS_LIST);
            }
            onSaveAddressList(addrList);                       
            return true;                     
        }                          
        return false;             
    }

    @Override
    protected void onPrepareRingtonePickerIntent(Intent intent) {
        // Remove all extras already placed by RingtonePreference
        intent.setAction(null);
        intent.removeExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
        intent.removeExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT);
        intent.removeExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI);
        intent.removeExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT);
        intent.removeExtra(RingtoneManager.EXTRA_RINGTONE_TYPE);

        // Set the activity we want to start.
        intent.setClass(getContext(), ContactPicker.class);

        // Addresses that was picked. So that your activity can handle it, s.t., checked them on/off.
        ArrayList addrList = onRestoreAddressList();
        if (addrList != null) {
            intent.putStringArrayListExtra(ContactPicker.EXTRA_ADDRESS_LIST, addrList);
        }
    }