Xamarin Android 7+以编程方式安装APK

时间:2017-07-10 14:18:50

标签: android xamarin xamarin.android

我正在尝试安装我已经下载到Android 7中的下载文件夹的.apk。

我尝试过使用FileProvider在一些StackOverflow帖子和https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en中推荐的方式:

File file = new File(fileUri);
//using Android.Support.V4.Content;
var downloadUri = FileProvider.GetUriForFile(context,context.ApplicationContext.PackageName + ".com.package.name.provider", file);
Intent install = new Intent(Intent.ActionInstallPackage);
install.AddFlags(ActivityFlags.GrantReadUriPermission);
install.AddFlags(ActivityFlags.GrantWriteUriPermission);
install.AddFlags(ActivityFlags.GrantPersistableUriPermission);
install.SetDataAndType(downloadUri, "application/vnd.android.package-archive");
context.StartActivity(install);

的AndroidManifest.xml

<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<application android:label="Settings" android:icon="@drawable/Icon" android:theme="@style/myTheme">
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.com.package.name.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

provider_paths.xml

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

“downloadUri”如下所示:“ content://com.package.name.com.package.name.provider/external_files/Download/Sensors%2520Multitool_1.3.0_apk-dl​​.com.apk

弹出安装窗口时的错误是:“解析包时出现问题”

我已经通过在downloads文件夹中单击它安装了这个软件包并且安装得很好,我也尝试了其他.apk的同样问题。

2 个答案:

答案 0 :(得分:3)

File file = new File(fileUri);
if(Build.VERSION.SdkInt >= Build.VERSION_CODES.N) {
    Uri apkUri = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", toInstall);
    Intent intentS = new Intent(Intent.ActionInstallPackage);
    intentS.SetData(apkUri);
    intentS.SetFlags(ActivityFlags.GrantReadUriPermission);
    context.StartActivity(intentS);
} else {
    Uri apkUri = Uri.FromFile(toInstall);
    Intent intentS = new Intent(Intent.ActionView);
    intentS.SetDataAndType(apkUri, "application/vnd.android.package-archive");
    intentS.SetFlags(ActivityFlags.NewTask);
    context.StartActivity(intentS);
}

答案 1 :(得分:0)

解析软件包的问题似乎是由于软件包名称“Sensors%2520Multitool_1.3.0_apk-dl​​.com.apk”中的空格。

删除空间后,包装正确安装。