1.添加未知来源的权限判断;
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
alertView = new AlertView("温馨提示", "请前往设置中开启安装应用所需的权限?", "取消", new String[]{"确定"}, null, this,
AlertView.Style.Alert, new OnItemClickListener() {
@Override
public void onItemClick(Object o, int position) {
if (position != AlertView.CANCELPOSITION) {
Uri packageURI = Uri.parse("package:" + getPackageName());
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
startActivityForResult(intent, PACKAGES_RESULT);
alertView.dismiss();
}
}
}).setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(Object o) {
}
});
alertView.show();
2.下载apk,注意下载apk的存放地址:
downloadFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "demo.apk");
3.下载完成后apk,安装:
try {
String[] command = {"chmod", "777", downloadFile.getAbsolutePath()};
ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
} catch (Exception ignored) {
ignored.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //android N的权限问题
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", downloadFile);//demo.apk是我们下载的apk的文件文成
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(downloadFile), "application/vnd.android.package-archive");//demo.apk的文件文成
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
activity.startActivity(intent);
注意几个地方:
1.配置文件共享
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="download"
path="" />
</paths>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.siyuzh.sywireless.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2.文件的下载地址
downloadFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "demo.apk");
3.7.0以上的安装