为什么 Intent.createChooser 正常工作时 Android resolveActivity 返回 null

Why does Android resolveActivity return null when Intent.createChooser works fine

提问人:Hector 提问时间:11/6/2023 更新时间:11/6/2023 访问量:37

问:

我当前的 Android 项目允许用户在浏览器中打开 Web 链接,或者发送并通过电子邮件发送到单击的电子邮件地址。

我构建我的意图如下:-

fun sendEmail(recipient: String, subject: String, message: String) {
    val uriText = "${EMAIL_MAIL_TO}${recipient}?subject=${subject}&body=${message}\n\n"

    val emailIntent = Intent(Intent.ACTION_SENDTO, Uri.parse(uriText)).apply {
        flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
        putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient))
        putExtra(Intent.EXTRA_SUBJECT, subject)
        putExtra(Intent.EXTRA_TEXT, message)
    }
    startActivity(Intent.createChooser(emailIntent, "Contact $recipient"))
}

fun openBrowser(url: String) {
    val browserIntent = Intent(Intent.ACTION_VIEW).apply {
        flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
        addCategory(Intent.CATEGORY_BROWSABLE)
        data = Uri.parse(url)
    }
    startActivity(Intent.createChooser(browserIntent, "Open Web Url"))
}

上面的代码既适用于发送电子邮件,也适用于在所需网页上打开设备 Web 浏览器。

当我用createChooser

if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
}

在这两种情况下,该函数都返回 null。resolveActivity

我做错了什么?

android-intent

评论


答:

1赞 VishnuPrabhu 11/6/2023 #1

https://developer.android.com/training/package-visibility/use-cases#check-browser-available

<- 放在 “” 元素内。-><queries>

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

评论

0赞 Hector 11/6/2023
是否有类似的发送电子邮件条目?
1赞 VishnuPrabhu 11/7/2023
我想你也回答了,我已经对更准确的答案投了赞成票。
1赞 Hector 11/6/2023 #2

这些清单条目解决了我的问题

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

奇怪的是,在我所有的像素测试设备上,我必须按两次后退才能返回我的应用程序,而在三星设备上,我只需要按一次后退。

评论

0赞 VishnuPrabhu 11/7/2023
您的Pixel和三星设备的版本是什么?