intent.resolveActivity returns null in API 30
Asked Answered
R

11

129

Looking at intent.resolveActivity != null but launching the intent throws an ActivityNotFound exception I wrote opening a browser or an application with Deep linking:

private fun openUrl(url: String) {
    val intent = Intent().apply {
        action = Intent.ACTION_VIEW
        data = Uri.parse(url)
//        setDataAndType(Uri.parse(url), "text/html")
//        component = ComponentName("com.android.browser", "com.android.browser.BrowserActivity")
//        flags = Intent.FLAG_ACTIVITY_CLEAR_TOP + Intent.FLAG_GRANT_READ_URI_PERMISSION
    }
    val activityInfo = intent.resolveActivityInfo(packageManager, intent.flags)
    if (activityInfo?.exported == true) {
        startActivity(intent)
    } else {
        Toast.makeText(
            this,
            "No application can handle the link",
            Toast.LENGTH_SHORT
        ).show()
    }
}

It doesn't work. No browser found in API 30 emulator, while a common solution works:

private fun openUrl(url: String) {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    try {
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        Toast.makeText(
            this,
            "No application can handle the link",
            Toast.LENGTH_SHORT
        ).show()
    }
}

The first method doesn't work, because intent.resolveActivityInfo or intent.resolveActivity returns null. But for PDF-viewer it works.

Should we dismiss intent.resolveActivity?

Reverie answered 23/6, 2020 at 13:25 Comment(2)
Assuming that you're targetting API level 30, that appears to be due to this: Package visibility in Android 11. Indeed, when I test your first snippet with an appropriate <queries> element in the manifest, it works as expected. If you'd rather not include such a <queries>, then you could just stick with the try-catch.Ado
@MikeM., thanks! Could you post it as an answer? I will later test it.Reverie
A
166

This appears to be due to the new restrictions on "package visibility" introduced in Android 11.

Basically, starting with API level 30, if you're targeting that version or higher, your app cannot see, or directly interact with, most external packages without explicitly requesting allowance, either through a blanket QUERY_ALL_PACKAGES permission, or by including an appropriate <queries> element in your manifest.

Indeed, your first snippet works as expected with that permission, or with an appropriate <queries> element in the manifest; for example:

<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
    </intent>
</queries>

The information currently available isn't terribly specific, but it does state:

The PackageManager methods that return results about other apps, such as queryIntentActivities(), are filtered based on the calling app's <queries> declaration

Though your example is using an Intent method – i.e., resolveActivityInfo() – that's actually calling PackageManager "query" methods internally. An exhaustive list of every method and functionality affected by this change might not be feasible, but it's probably safe to assume that if PackageManager is involved, you might do well to check its behavior with the new restrictions.

Ado answered 12/7, 2020 at 3:24 Comment(8)
Worked for me except there's a warning: Element category is not allowed here.Returnable
@Westy92, Google removed this warning.Reverie
Could you explain why the BROWSABLE category is recommended for this? Things seem to work the same without itIkey
Would be nice if there was some sort of Warning/Error thrown letting you know you need to add that in the manifestCrosspollinate
probably you need this: #62970417Torras
@Returnable My guess is <category> belongs only to <intent-filter>, we don't need that for <intent> I searched for a few examples in Android official docs, I see that it is listed only under <intent-filter> developer.android.com/guide/components/…Plexiform
I have needed queries in the manifest and it still doesn't work #73435247Laclair
Didn't work for opening "youtu.be" url. That's why I've chosen try catch solutionPlacentation
R
120

Thanks to Mike M. I added queries for Browser, Camera and Gallery. Place them inside AndroidManifest in any part of it (before or after <application> tag).

Looking at MediaStore.ACTION_IMAGE_CAPTURE and Intent.ACTION_GET_CONTENT I got both actions.

<queries>
    <!-- Browser -->
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="http" />
    </intent>

    <!-- Camera -->
    <intent>
        <action android:name="android.media.action.IMAGE_CAPTURE" />
    </intent>

    <!-- Gallery -->
    <intent>
        <action android:name="android.intent.action.GET_CONTENT" />
    </intent>
</queries>

Dylan answer was not required to me, so I still have

<uses-feature
    android:name="android.hardware.camera"
    android:required="false"
    />
Reverie answered 5/10, 2020 at 8:3 Comment(5)
Right answer, Thanks, Now working fine in Android 11 One plus device.Conformable
Do here is any difference in <data android:scheme="https" /> or <data android:scheme="http" /> ? what if I may access both https and http in different button of my app? I need to add two <!-- Browser --> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="http" /> </intent> <!-- Browser --> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="https" /> </intent> or <data android:scheme="http" /> <data android:scheme="https" /> in one tag?Infallible
@Raii, currently I don't know. I used http for both cases. Do you want to know if a device has a browser? Or do you want to launch your application by a link? In second case you are to learn Deep Linking.Reverie
@Reverie I just want to go to the Google Play Shop for my app, I have used some lines of code (the shop link is https) for years but recently I find the warning and I see this post I need to add <queries>...</queries> to handle this and I see one answer saying http and another answer saying https @@Infallible
@Raii, thanks! You can use https only for https:// addresses. Currently it's enough for your task. If you set http instead of https you will open both https:// and http:// domains. So, it's up to you, what you prefer more.Reverie
T
47

For me I was trying to send an email so I needed to set the queries in the Manifest like this:

<queries>
    <intent>
        <action android:name="android.intent.action.SENDTO" />
        <data android:scheme="*" />
    </intent>
</queries>

then send email and check for email clients like this:

        private fun sendEmail(to: Array<String>) {
        val intent = Intent(Intent.ACTION_SENDTO)
        intent.data = Uri.parse("mailto:") // only email apps should handle this
        intent.putExtra(Intent.EXTRA_EMAIL, to)
//        intent.putExtra(Intent.EXTRA_SUBJECT, subject)
        if (intent.resolveActivity(requireContext().packageManager) != null) {
            startActivity(intent)
        }
    }
Taxonomy answered 6/12, 2020 at 8:21 Comment(3)
This is not mentioned on androids official link , which teaches how to send emails developer.android.com/guide/components/intents-common#Email. I hate this platform often , It makes me want to pull all my hair out .Aerify
Totally agree @muhammad-ahmed-abutalib . For me, <data android:scheme="mailto" /> worked.Maverick
This solution works for me, however, if I go back from the email app, then I need to tap the button twice to open the activity, even though "intent.resolveActivity(context.packageManager)" is not null.Benzoate
E
32

For cases when need to start an Activity (not only check if exist), following this advise I removed

if (intent.resolveActivity(packageManager) != null)
                startActivity(intent);

and wrote instaed

try {
     startActivity(intent);
} catch (ActivityNotFoundException e) {
     Toast.makeText(getContext(), getString(R.string.error), Toast.LENGTH_SHORT).show();
}

No need to add any <queries> at the Manifest. Tested on both Api 28 and Api 30.

Exhortative answered 21/1, 2021 at 8:33 Comment(4)
This is a case when you have to start an activity. But there may be a situation when you need to know if there are applications, but not start them.Reverie
Thanks! I didn't notice that. I Edit the answerExhortative
@Reverie You could have mentioned an example. I only can imagine to hide some controls if there is no app installed to handle it. For example: I don't need a photo button if there's no camera app.Estancia
@TheincredibleJan, yes. If you want to have an example, there may be situations when you have to choose whether to start an application or handle yourself. For instance, an application will show one screen if there are registered applications of your company in this device, or usual screen in other cases. Or your application can be opened by Deep Link and edit e-mail message, then send it via e-mail client. But if there are no e-mail clients, it should open another screen or close itself, for instance. I didn't try these schemes.Reverie
K
6

To iterate on Avital's answer, you don't need to declare anything if you want to launch an intent and get to know whether it's been launched:

private fun startIntent(intent: Intent): Boolean {
    return try {
        context.startActivity(intent)
        true
    } catch (e: ActivityNotFoundException) {
        Logger.error("Can't handle intent $intent")
        false
    }
}
Kathaleenkatharevusa answered 17/6, 2021 at 7:59 Comment(0)
B
1

You may add QUERY_ALL_PACKAGES permission in AndroidManifest. It doesn't require run-time permission request.

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
Bacteroid answered 27/5, 2021 at 9:34 Comment(1)
Yes, but Google Play restricts the use of high risk or sensitive permissions, including the QUERY_ALL_PACKAGES permission, which gives visibility into the inventory of installed apps on a given device.Reverie
E
1

My solution

add this to manifest

<queries>
    <intent>
        <action android:name="android.media.action.IMAGE_CAPTURE" />
    </intent>
</queries>

use this function

private File create_image() throws IOException {
    @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "img_" + timeStamp;
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return new File(storageDir, imageFileName + ".jpg");
}

use this for Android 10

<application
     android:requestLegacyExternalStorage="true"
     ...

</application>
Erund answered 29/11, 2022 at 16:16 Comment(0)
B
0

What Mike said in addition to the code below is what worked for me.

<manifest ... >
    <uses-feature android:name="android.hardware.camera"
                  android:required="true" />
    ...
</manifest>
Benempt answered 29/9, 2020 at 14:22 Comment(0)
A
0

In the case you are using the intent action ACTION_INSERT, per documentation, you need to add the intent-filter to the using activity with the action INSERT and with the specified mimeType, to have intent.resolveActivity(view.context.packageManager) != null return true.

<activity ...>
<intent-filter>
    <action android:name="android.intent.action.INSERT" />
    <data android:mimeType="vnd.android.cursor.dir/event" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Altman answered 20/1, 2022 at 23:3 Comment(0)
U
0

As the question raised by the user has not set any limitations so simply you can do like this and it will DIRECTLY NAVIGATE to the GMAIL with the EMAIL ID you passed in the INTNET

val emailTo = "[email protected]" // just ex. write the email address you want
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("mailto:$emailTo")
startActivity(intent) // <---- this is work for activity and fragment both
Unmusical answered 25/4, 2022 at 5:29 Comment(2)
I suppose, it will work if a device contains email applications. If not, it will crash.Reverie
Yes we can assume that but nowadays no device in android have seen without an email or Gmail app or else we can just use the above answers as well as we can use try catchUnmusical
A
0

Replace

val activityInfo = intent.resolveActivityInfo(packageManager, intent.flags)
    if (activityInfo?.exported == true) {
        startActivity(intent)
    } else {
        Toast.makeText(
            this,
            "No application can handle the link",
            Toast.LENGTH_SHORT
        ).show()
    }

With

if (requireActivity().packageManager.resolveActivity(intent,0) != null){
    startActivity(intent)
}else{
    Toast.makeText(
        this,
        "No application can handle the link",
        Toast.LENGTH_SHORT
    ).show()
}
Alejandroalejo answered 9/7, 2022 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.