2010-08-25 100 views
5

我有一个应用程序,我想添加自动更新功能(它不在市场上)。我已经具备了所有的代码,将检查是否有可用的更新,然后我把这样的事情:Android:下载后自动更新如何打开apk文件?

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

其开始下载文件。有没有一种方法可以通过编程方式让它“打开”文件以开始安装过程,而无需用户进行下载并单击它?

回答

6

这将开始安装过程

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); 
+0

这就不管用了,你的应用程序的目标API 24以上。请参阅下面的答案 – 2016-12-02 20:32:26

4

答案以上是预API-24。

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

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>