繁体   English   中英

Android:下载自动更新后如何打开apk文件?

[英]Android: how to open an apk file after downloading for auto-update?

我有一个想要添加自动更新功能的应用程序(它不在市场上)。 我已经准备好了所有代码,以检查是否有可用的更新,然后调用如下代码:

Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse(Configuration.APK_URL));
c.startActivity(intent);  

开始下载文件。 有没有一种方法可以使我以编程方式告诉它“打开”文件以开始安装过程,而无需用户下载文件并单击它?

上面的答案是针对API-24之前的版本。

如果您的应用程序的目标API 24以上(应该),你需要使用别的东西(否则你FileUriExposedException,如所描述这里 ):

    File apkFile = new File(...);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri fileUri = android.support.v4.content.FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", apkFile);
    intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);

provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!--<external-path name="external_files" path="."/>-->
    <external-path path="Android/data/YOUR_PACKAGE_NAME" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>

其中YOUR_PACKAGE_NAME是您应用的程序包名称。

表现:

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

这将开始安装过程

File apkFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/packageName.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(intent);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM