/*重点:需要调用该方法动态授权执行本地文件处理,否则无效。
*/
private void permissiongen() {
//处理需要动态申请的权限
PermissionGen.with(MainActivity.this)
.addRequestCode(200)
.permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
.request();
}
//申请权限结果的返回
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}
//权限申请成功
@PermissionSuccess(requestCode = 200)
public void doSomething() {
try {
//在这个方法中做一些权限申请成功的事情
String downloadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download";
File file = new File(downloadPath);
if (!file.exists()) {
file.mkdirs();
}
currery.downloadPath = downloadPath;
String filePath = httpGet.getUrlApk(MainActivity.this, url);
if (currery.proDiaLog != null) {
currery.proDiaLog.dismiss();
}
if (!filePath.equals("")) {
httpGet.installApk(getApplicationContext(), filePath);
} else {
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
if (currery.proDiaLog != null) {
currery.proDiaLog.dismiss();
}
}
}
/**
* @param httpUrl=请求地址
* @return
*/
public static String getUrlApk(Activity act, String httpUrl) {
String filePath = "";
try {
URL url = new URL(httpUrl);//创建一个URL对象,其参数为网络的链接地址
//使用一个URL对象开启一个链接
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//设置相关参数
con.setDoInput(true);
con.setConnectTimeout(20000);//设置超时
con.setReadTimeout(20000);
con.connect();
InputStream is = con.getInputStream();//获取输入流
FileOutputStream fos = new FileOutputStream(new File(currery.downloadPath + "/aaa.apk"));
byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
filePath = currery.downloadPath + "/aaa.apk";
} catch (Exception e) {
Toast.makeText(act, e.getMessage(), Toast.LENGTH_LONG).show();
}
return filePath;
}
/**
* 安装apk文件
*
* @param filePath
*/
public static void installApk(Context act, String filePath) {
File apkfile = new File(filePath);
if (!apkfile.exists()) {
return;
}
Intent intentUpdate = new Intent("android.intent.action.VIEW");
intentUpdate.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
File file = new File(filePath);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //对Android N及以上的版本做判断
Uri apkUriN = FileProvider.getUriForFile(act,
act.getApplicationContext().getPackageName() + ".provider", file);
intentUpdate.addCategory("android.intent.category.DEFAULT");
intentUpdate.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加Flag 表示我们需要什么权限
intentUpdate.setDataAndType(apkUriN, "application/vnd.android.package-archive");
} else {
Uri apkUri = Uri.fromFile(file);
intentUpdate.setDataAndType(apkUri, "application/vnd.android.package-archive");
}
act.startActivity(intentUpdate);
}