0

My app is crashing on some devices with an error android.content.ActivityNotFoundException. After looking up in Android Vitals Crashes section, the following function is causing it to crash:

private void openUrl(String url) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

It is an intent to open play store page of my app with url as my play store app link. I couldn't able to reproduce the crash in any of my devices. Any help will be appreciated.

Jazib Khan
  • 408
  • 4
  • 13

1 Answers1

1

There is no guarantee that any given ACTION_VIEW Intent will work. For example, the active user may have a restricted profile or be part of some work profile where they lack access to whatever it is that you are trying to start.

The safest solution, with Android 11 in mind, is to catch the exception:

private void openUrl(String url) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    try {
      startActivity(i);
    } catch (Exception e) {
      // do something to tell the user "sorry!"
    }
}
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491