6

In my android application I want the user to choose, which other application should be used to display a certain image if there are more than one possible apps. Therefore I got following code:

final Intent intent = new Intent(Intent.ACTION_VIEW)
                       .setDataAndType(uri, IMAGE_MIME_TYPE)
                       .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NO_HISTORY);

 context.startActivity(intent);

As intented an app chooser is displayed.

Right before I call startActivity I open a ProgressDialog, which I want to close when for example the user cancels the app chooser via back button. What is the best way to identify that the app chooser was canceled? In other words - where should I close my ProgressDialog?

c7n
  • 1,131
  • 16
  • 29
  • Probably there's better solutions, but as you said, you could check in the backbuttonpressed for it. Though might not be the only way to cancel it – Memme Jul 05 '16 at 08:17
  • I think it may be a typo - but you name your `Intent` `intent` and open `viewIntent`. Maybe change it to the right variable. :) – yennsarah Jul 05 '16 at 08:23
  • thanks for pointing that out - was a typo :) – c7n Jul 05 '16 at 08:23

1 Answers1

8

Start an activity like this:

 context.startActivityForResult(viewIntent, <int flag>);

Then in onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == <int flag>) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // The user pressed ok
        }else{
            // The user pressed cancel 
        }
    }
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113
  • 1
    when trying like that, `onActivityResult` is called instantly after `startActivityForResult` with resultCode 0 `RESULT_CANCELED` even before I actually canceled the intent chooser – c7n Jul 05 '16 at 08:52
  • this happens because of `Intent.FLAG_ACTIVITY_NEW_TASK` flag – Jignesh Ansodariya Jul 05 '16 at 10:51
  • @JigneshAnsodariya But when i pressed ok. It is not triggering toast message. but, cancel was showing toast why ? –  Sep 10 '20 at 08:07