先上代码,代码兼容7.0
/**
* 安装apk
*/
private void installApk() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
}
intent.setDataAndType(uri, type);
activity.startActivity(intent);
}
对于需要兼容7.0需要在在AndroidManifest中添加provider
<application
...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
</application>
上段代码中的file_paths是定义在res下的xml文件夹中的文件
<paths>
<external-path name="external_storage_root" path="." />
</paths>
其中external-path节点表示Environment.getExternalStorageDirectory()路径
path表示apk文件在Environment.getExternalStorageDirectory()路径下的文件夹名称
最后如果需要兼容8.0手机需要添加权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
附上两个方法
获取当前版本号
try {
PackageManager manager = activity.getPackageManager();
PackageInfo info = manager.getPackageInfo(activity.getPackageName(), 0);
versionCode = info.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
获取apk文件版本号
private int getVersionCodeFromApk(String path) {
PackageManager pm = activity.getPackageManager();
PackageInfo packInfo = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
int versionCode;
try {
versionCode = packInfo.versionCode;
} catch (Exception e) {
versionCode = 0;
}
return versionCode;
}