You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击地图商店列表项时,如何弹出地图应用选择对话框?

解决地图应用选择器不弹出的问题

你的代码直接打开Google Maps,是因为系统可能将其设为了geo: URI的默认处理应用,或者选择器没有正确识别到其他支持的地图应用。以下是修改方案:

核心修改代码

fun openMapApp(office: StoreOffice) {
    weakReference.get()?.run {
        val location = "${office.latitude},${office.longitude}"
        val vendorLabel = office.vendorName
        // 基础地图跳转Intent
        val baseMapIntent = Intent(Intent.ACTION_VIEW, Uri.parse("geo:$location?q=$location($vendorLabel)"))

        val packageManager = requireContext().packageManager
        // 查询所有支持该Intent的应用
        val availableMapApps = packageManager.queryIntentActivities(baseMapIntent, PackageManager.MATCH_DEFAULT_ONLY)

        if (availableMapApps.isEmpty()) {
            // 无可用地图应用时显示提示
            AlertDialog.Builder(requireContext())
                .setTitle(R.string.common_warning)
                .setMessage(R.string.app_not_found_message)
                .setPositiveButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
                .show()
            return@run
        }

        // 为每个地图应用创建单独的Intent
        val targetIntents = mutableListOf<Intent>()
        availableMapApps.forEach { resolveInfo ->
            val appPackage = resolveInfo.activityInfo.packageName
            val appIntent = Intent(baseMapIntent).apply {
                setPackage(appPackage)
            }
            targetIntents.add(appIntent)
        }

        // 构建应用选择器
        val chooserIntent = Intent.createChooser(targetIntents.removeAt(0), resources.getString(R.string.chooser_title))
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toTypedArray())

        try {
            startActivity(chooserIntent)
        } catch (e: ActivityNotFoundException) {
            AlertDialog.Builder(requireContext())
                .setTitle(R.string.common_warning)
                .setMessage(R.string.app_not_found_message)
                .setPositiveButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
                .show()
        }
    }
}

关键改动说明

  • 手动枚举可用应用:通过packageManager.queryIntentActivities获取所有支持geo: URI的地图应用,确保不会遗漏Yandex Maps这类应用。
  • 构建专属Intent:为每个应用单独创建Intent并指定包名,强制系统弹出选择器,不受默认应用设置影响。
  • 修复提示对话框:补充setPositiveButton并调用show(),确保无可用应用时用户能看到提示(原代码仅创建了对话框但未显示)。

扩展:兼容Yandex Maps专属协议

如果Yandex Maps对geo: URI支持不佳,可以额外添加其专属协议的Intent,确保被纳入选择列表:

// 在构建targetIntents后添加以下代码
val yandexMapIntent = Intent(Intent.ACTION_VIEW, Uri.parse("yandexmaps://maps.yandex.ru/?ll=$location&text=$vendorLabel"))
if (packageManager.resolveActivity(yandexMapIntent, 0) != null) {
    targetIntents.add(yandexMapIntent)
}

内容的提问来源于stack exchange,提问作者Ae.S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:20:16