So I can display Android's contact selecton activity by calling
startActivityForResult(intent, PICK_CONTACT);
and i can get the selecte开发者_开发技巧d contact by overriding onActivityResult
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
}
Trouble is onActivityResult is only available when I am calling from an Activity myself. If I am in a DialogPreference for instance how would i get at the selected contact because I do not have an onActivityResult to override ?
TIA
Pat Long
So I know this problem is old and has been answered, but I was having the same problems mentioned in the comments. I had this problem trying to launch an ACTION_GET_CONTENT intent from a class I derived from Preference. Using Pentium10's suggestion, I created a new class derived from Activity to launch the intent and grab the result. I called this class SurrogateActivity and it looks like this:
public class SurrogateActivity extends Activity {
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
Intent chooseFileIntent = new Intent();
chooseFileIntent.setAction(Intent.ACTION_GET_CONTENT);
// In my case I need an audio file path
chooseFileIntent.setType("audio/*");
startActivityForResult(chooseFileIntent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
Uri audioPath = data.getData();
// Use SharedPreferences.Editor to update preference value
SharedPreferences.Editor prefsEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
prefsEditor.putString(Keys.PREF_ALERT, audioPath.toString());
prefsEditor.commit();
}
// finish this "hidden" activity on any result
finish();
}
}
In my custom Preference class, I wanted the picker to launch when the use taps the preference. I set onClick() to launch my SurrogateActivity class which then in turn launches the intent I really need in its onCreate method.
@Override
protected void onClick(){
super.onClick();
Intent launchHiddenActivity = new Intent(getContext(), SurrogateActivity.class);
getContext().startActivity(launchHiddenActivity);
}
Pentium10 suggested a private class inside your Preference class, but when I tried this, Android couldn't instantiate it. Also, remember to add your "surrogate activity" to your manifest.
I know you want to create a custom DialogPreference to Pick a Contact as proposed in the other question, you indeed need to launch the intent to pick the contact and get the result.
I see you need to create a private class that extends Activity in your own DialogPreference class. And you will use that class and the onActivityResult.
You are doing a great job, keep up the good work.
精彩评论