之前做过有关安卓部分的下载和自动安装打开,忘记记录了,现在补上
代码如下:
public class MainActivity extends BaseActivity {
public static MainActivity instance = null;
public String mLocalVersionName = "";//定义当前的APP版本号
private ProgressDialog mDialog;//下载更新的进度条提示框
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//获取软件版本号,对应AndroidManifest.xml下android:versionCode
mLocalVersionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
//这里是请求后台接口,获取服务器上传的APP版本号,然后调用checkversion方法,用本地的和后台的服务器版本做对比,如果版本不一样就提示更新
OkHttpUtils.post()
.url(Constant.BASEURL)
.addParams("type", "0")
.build().execute(new StringCallback() {
@Override
public void onError(Request request, Exception e) { }
@Override
public void onResponse(String response) {
UpdataSystem bean = new Gson().fromJson(response, UpdataSystem.class);
checkVersion(bean.getExtend().getString());//传入后台的版本号,对比
}
});
}
public void checkVersion(String netVersionName) {
if (!mLocalVersionName.equals(netVersionName)) {
loadNewVersion();//发现新版本就更新
} else {
}
}
private void loadNewVersion() {
final String url = Constant.Url + "pic/app/xxx.apk";//这里是链接文件的地址
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMax(100);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.show();
OkHttpUtils.get().url(url).build()
.execute(new FileCallBack(getExternalCacheDir().getAbsolutePath(), "app.apk") {
@Override
public void inProgress(float progress) {
//进度条的更新
mDialog.setProgress((int) (100 * progress));
}
@Override
public void onError(Request request, Exception e) { }
@Override
public void onResponse(File response) {
//下载完毕之后走这个方法,安装应用并自动打开
excutesucmd(String.valueOf(response));
}
});
}
protected void excutesucmd(String currenttempfilepath) {
Process process = null;
OutputStream out = null;
InputStream in = null;
try {
// 请求root
process = Runtime.getRuntime().exec("su");
out = process.getOutputStream();
// 调用安装
out.write(("pm install -r " + currenttempfilepath + "\n").getBytes());
in = process.getInputStream();
int len = 0;
byte[] bs = new byte[256];
while (-1 != (len = in.read(bs))) {
String state = new String(bs, 0, len);
if (state.equals("success\n")) {
//安装成功后的操作
//静态注册自启动广播
Intent intent = new Intent();
//与清单文件的receiver的anction对应
intent.setAction("android.intent.action.PACKAGE_REPLACED");
//发送广播
sendBroadcast(intent);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
网友评论