java - 打开 URL 的 Intent 不适用于一个应用程序,但适用于另一个应用程序

标签 java android url android-intent android-gradle-plugin

我的应用程序想要通过此方法打开一个网络链接(例如 https://www.google.com ):

public void openUrl(Activity activity, String urlParam) {
    String url = Uri.encode(urlParam);
    Intent browserIntent = new Intent(Intent.CATEGORY_BROWSABLE, Uri.parse(url));

    browserIntent.setAction(ACTION_VIEW);

    activity.startActivity(browserIntent);
}

我收到此错误:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://www.google.com }

如果我让应用程序调用选择器供用户选择应用程序,设备上会出现一条消息,指出没有应用程序可以处理该操作。

startActivity(Intent.createChooser(intent, "浏览方式"));

所以,这也行不通。

这很奇怪,我看到很多类似的问题但没有解决方案。网址正确。

这是 Gradle 文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

这怎么可能?我有另一个使用类似代码的应用程序,它能够调用浏览器在同一设备上显示 URL。

这是它的 Gradle 文件:

apply plugin: 'android'

android {
    //noinspection GradleCompatible
    compileSdkVersion 28
    buildToolsVersion '28.0.3'

    defaultConfig {
        applicationId "com.myappname.app"
        versionCode 62

        minSdkVersion 19
        targetSdkVersion 28
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:28.0.0'
}

如何解决这个问题?

最佳答案

实际问题在于 Uri.encode(urlParam) 的使用。您正在对 URL 进行编码,但稍后您不会对其进行解码,以便 ACTION_VIEW 理解 Intent 数据!

    String url = "https://www.google.com/";
    String query = Uri.encode(url, "UTF-8");
    Intent browserIntent = new Intent(CATEGORY_BROWSABLE, Uri.parse(Uri.decode(query)));
    browserIntent.setAction(ACTION_VIEW);
    startActivity(browserIntent);

关于java - 打开 URL 的 Intent 不适用于一个应用程序,但适用于另一个应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60038310/

相关文章:

python - 在某些字符串上匹配正则表达式的 URL 非常慢

Python ASCII 编解码器在写入 CSV 时无法编码字符错误

java - PreparedStatement 的 setInt() 不适用于 PostgreSQL

java - 空对象引用上的 Model.Result.getFormatted_address()'

java - 如何在 Long 方法中返回 a 和 b 相加的结果?

android - 在Android扩展列表中,如何在组扩展时获取当前 View ?

java - 类实例问题,Android

php - 一次从多个 url 获取 XML 数据失败

java - Log4j 滚动文件附加程序 : include timestamp in filename

java - 序列化扩展map的json对象