版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26841579/article/details/80775101
1,开发中遇到没有内置SDK的情况。之前没搞过,今天搞了一下午。终于找到原因了,特此记下来。
首先感谢这位:http://aijiawang-126-com.iteye.com/blog/792931
我的网络请求用的是OKGO。
直接贴代码
/**
* APP下载
*
* @param url
* @param fileName APP名字 最近从新命的名字
*/
public void downLoadApp(String url, final String fileName) {
OkGo.<File>get(url)
.tag(this)
.execute(new FileCallback(getApplicationContext().getDir("app", MODE_WORLD_WRITEABLE) + "/", fileName) {
@Override
public void onStart(Request<File, ? extends Request> request) {
super.onStart(request);
//6.0 以上要手动给权限。
verifyStoragePermissions(GameActivity.this);
// crateFile("");
showDialog();
}
@Override
public void onSuccess(Response<File> response) {//
hud.dismiss();
// 这个是关键,给指定文件权限
setUpdateDir(new File(getApplicationContext().getDir("app", MODE_WORLD_WRITEABLE) + "/" + fileName));
//安装APP
installApp(getApplicationContext().getDir("app", MODE_WORLD_WRITEABLE) + "/" + fileName);
}
@Override
public void onError(Response<File> response) {
super.onError(response);
Toast.makeText(GameActivity.this, "下载失败,请检查!", Toast.LENGTH_SHORT).show();
}
@Override
public void downloadProgress(Progress progress) {
super.downloadProgress(progress);
Log.e("包路径---", "" + progress.fraction);
}
@Override
public void onFinish() {
super.onFinish();
hud.dismiss();
}
});
}
下面是两个方法
//根据指定路径安装APP
private void installApp(String path) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + path),
"application/vnd.android.package-archive");
startActivity(intent);
}
/**
* 内置存储中给指定的文件权限。
*
* @param updateDir 文件路径位置
*/
private void setUpdateDir(File updateDir) {
try {
Process p = Runtime.getRuntime().exec("chmod 777 " + updateDir);
int status = p.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}