首页 > 解决方案 > 如何将我的应用程序中的 apk 共享到 android 中的 whatsapp?

问题描述

当按下某个按钮时,我想与 WhatsApp 共享一个应用程序 apk。这是我的尝试和情况:代码如下:

public void onClick(View view) {
                Uri uri;
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setType("plain/text");
                uri = Uri.parse("android.resource://com.simon.easycounter/counter.apk");
                sendIntent.putExtra(Intent.EXTRA_STREAM,uri);
                sendIntent.setPackage("com.whatsapp");
                startActivity(sendIntent);
           }

apk 文件位于包 com.simon.easycounter 中,Java 类文件所在的位置。

我尝试了很多不同的文件路径,我尝试了不同的 MIME 类型,如“ / ”、“application/*”,但没有任何效果。当按下 WhatsApp 中的发送按钮时,会出现一条来自 WhatsApp 的消息,上面写着“共享失败,请稍后再试”。

有谁知道如何解决这个问题?

- -更新 - -

我现在创建了一个 FileProvider:

在我的 Manifest.xml 中:

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"/>
        </provider>

我的 filepaths.xml 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <files-path name="files" path="/" />
        <cache-path name="cache" path="/"/>
    </paths>

</PreferenceScreen>

这是我按下按钮时更新的代码:

public void onClick(View view) {
                File newFile = getActivity().getFileStreamPath("counter.apk");
                Uri uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID, newFile);

                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setType("application/vnd.android.package-archive");
                sendIntent.putExtra(Intent.EXTRA_STREAM,uri);
                sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                sendIntent.setPackage("com.whatsapp");
                startActivity(sendIntent);
}

这是将apk复制到文件并创建Uri的正确方法吗?它不起作用的问题是什么?WhatsApp上的错误消息仍然相同

标签: androidandroid-intentfilepathfile-sharing

解决方案


推荐阅读