Why is a Intent started before an AlertDialog.Builder, even if it's coded the other way round
With the following code, the Intent is started when calling newPicture, and the Dialog is shown afterwards. What does this, and how can I change the order?
public void newPicture(View v) {
SharedPreferences settings = getPreferences(MODE_PRIVATE);
boolean geoProtipAlreadyShown = settings.getBoolean("geoProtipAlreadyShown", false);
if (!geoProtipAlreadyShown) {
showGeoProtip();
// and set the option in SharedPreferences
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("geoProtipAlreadyShown", true);
editor.commit();
}
// start the image开发者_开发技巧 capture activity
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(PATH, "tmpfile.jpg")));
startActivityForResult(intent, IMAGE_CAPTURE);
}
private void showGeoProtip() {
String geoProtip = this.getResources().getString(R.string.protip);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(geoProtip).setCancelable(true).setPositiveButton("OK", null);
AlertDialog alert = builder.create();
alert.show();
}
Move the start image capture activity to new method, and put it to dialog's OnClickListener:
builder.setMessage(geoProtip).setCancelable(true).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
captureImage();
}
});
private void captureImage(){
// start the image capture activity
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(PATH, "tmpfile.jpg")));
startActivityForResult(intent, IMAGE_CAPTURE);
}
And modify if-else:
if (!geoProtipAlreadyShown) {
showGeoProtip();
....
}else{
captureImage();
}
Move your intent sending to the onclicklistener of one of the buttons of the dialog.
This is a classic gotcha for Android programmers. Basically showing the alert does not halt the execution of the code, so you have to start the intent inside an onclicklistener.
I think this will be useful
Dialog dlg = new AlertDialog.Builder(context)
.setTitle("TITLE")
.setMessage("MSG")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Write the intent here.
}
})
.create();
dlg.show();
精彩评论