2010-08-25 97 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>