您的位置:首页 > 移动开发 > Android开发

android实现静默更新安装并自动启动

2017-12-22 16:53 274 查看
因为做的项目是装在固定设备上的,所有设备都已root

一:当前版本号与服务器版本对比 如有更新则去服务器下载新版本

这个网上很多教程不多说

二:下载完保存到某目录下,自动安装,无需手动点击确认

实现实际使用的是su pm install -r filepath命令。

核心代码如下:

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();
}
}
}

三、自启动

注册广播UpdateRestartReceiver,监听是否重新装了安装包
public class UpdateRestartReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")){
//Toast.makeText(context,"已升级到新版本",Toast.LENGTH_SHORT).show();

Intent intent2 = new Intent(context, SplashActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);

}
}
}

AndroidManifest.xml中
<receiver android:name=".updateversion.UpdateRestartReceiver"
>
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<data android:scheme="package"/>
</intent-filter>

</receiver>

静态注册启用广播:

//静态注册自启动广播

Intent intent=new Intent();

//与清单文件的receiver的anction对应

intent.setAction("android.intent.action.PACKAGE_REPLACED");

//发送广播

sendBroadcast(intent);

所需权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name= "android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: