安装应用一般需要添加的权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REPLACE_EXISTING_PACKAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
在AndroidManifest.xml文件中application中添加如下权限,该权限适用于Android 10.0
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
判断点击文件是否为apk,并且适配Android 5.0 到Android 10.0
导入包:import androidx.core.content.FileProvider;
else if(TypeFilter.getInstance().isApkFile(item_ext)){
if(file.exists()) {
if(mReturnIntent) {
returnIntentResults(file);
} else {
try {
Intent installIntent = new Intent();
installIntent.setAction(Intent.ACTION_VIEW);
Uri apkUri = FileProvider.getUriForFile(getApplicationContext(), "com.softwinner.explore.fileprovider", file);///-----ide文件提供者名
int version = android.os.Build.VERSION.SDK_INT;
if (version > 24) {//android 7.0-10.0及以上版本
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {//android 5.0-7.0
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
startActivity(installIntent);
}catch (IllegalArgumentException e){
}
}
}
}
在AndroidManifest.xml文件中添加provider
<provider
android:authorities="com.softwinner.explore.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
在res目录下面创建一个xml文件,在该文件中创建filepaths文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path path="" name="cmrootfile" />
<files-path path="" name="cmfiles" />
<cache-path path="" name="cmcache" />
<external-path path="" name="cmexternal" />
<external-files-path path="" name="cmexternalfile" />
<external-cache-path path="" name="cmexternalcache" />
</paths>
备注说明:
Android10 中使用FileProvider需要导入FileProvider包
import androidx.core.content.FileProvider;
在build.gradle文件中添加androidx的依赖
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'