天天看點

Android使用Intent跳轉APK安裝

Android7.0之前的跳轉

Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri ,"application/vnd.android.package-archive");
startActivity(intent);
           

Android7.0的跳轉

要在AndroidManifest.xml中定義FileProvider

<provider
	android:name="androidx.core.content.FileProvider"
    android:authorities="包名.fileprovider"	
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_provider_path" />
</provider>
           

file_provider_path為調用的資源檔案。

需在AndroidManifest.xml的同級目錄建立一個xml檔案夾,然後在裡面建立一個xml檔案,檔案名随意。

根據自己的需求在file_provider_path.xml檔案裡面寫相應的。

provider_paths.xml

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

	<!--external-path 對應 Environment.getExternalStorageDirectory()-->
    <external-path name="name" path="."  />
    
    <!--files-path對應Context.getFilesDir()-->
    <files-path name="name" path="." />
    
	<!--cache-path對應Context.getCacheDir()-->
	<cache-path name="name" path="." />

	<!--external-files-path對Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)-->
	<external-files-path name="name" path="path" /> 

	<!--external-cache-path對應Context.getExternalCacheDir()-->
	<external-cache-path name="name" path="path" /> 

	<!--cache-path對應Context.getExternalMediaDirs()(API21+)-->
	<external-media-path name="name" path="path" /> 
</paths>
           
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
	intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
	uri=FileProvider.getUriForFile(this,"項目包名.fileprovider",file);
}else{
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    uri = Uri.fromFile(file);
}
intent.setDataAndType(uri ,"application/vnd.android.package-archive");
startActivity(intent);
           

Android8.0,9.0的跳轉

代碼和7.0的一樣隻不過要在AndroidManifest.xml檔案中添加

//申請未知來源權限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
           
上一篇: IntentIntent
下一篇: Intent種類