Android App 静默升级

app静默安装的意思也就是不用手动去点击安装,完全自动化,无需人工操作。但是前提是app必须有系统权限。

由于我做的是定制化的,所用的系统是8.0有效,其他没测试过。

1、app应用必须经过系统签名,怎么签名我这就不说了,可以查一下其他资料

2、apk下载过程可以参考 https://blog.csdn.net/why_111/article/details/107211511 

3、有了系统权限之后 ,记得在Manifest.xml目录下添加 :

android:sharedUserId="android.uid.system"

3、安装apk

// true :安装成功  
public  boolean install(String apkPath) {// apkPath:apk的存储路径
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            LOG.info("要安装的apk路径:" + apkPath);
            String command = "pm install -t -r " + apkPath + "\n";// -t:允许apk被安装  -r :重新安装应用,且保留应用数据
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            LOG.info( "install msg is " + msg);
            // 如果执行结果中包含Failure字样就认为是安装失败,否则就认为安装成功
            if (!msg.contains("Failure")) {
                result = true;
            }

        } catch (Exception e) {
            //ToastUtil.showLongToast(KursaalApp.context,"设备未Root,请先Root后再继续使用!");
            LOG.info( e.getMessage(), e);
            result = false;
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                result = false;
                LOG.info( "install: " + e.toString());
            }
        }
        return result;
    }

判断没有rott权限可以用一下方法:

  /**
     * 判断手机是否拥有Root权限。
     *
     * @return 有root权限返回true,否则返回false。
     */
    public static boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

安装成功之后有一个问题,app不会自动重启,这个时候可以写一个广播来接收是否已经安装成功。

我也查了很多资料,看网上写的广播我并接收不到,后来在注册广播的时候有添加了一条action,

<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>

发现只能接收到我自己app下载完成的广播,不过这到也可以,也省的再去判断是否是自己的app升级了。

完整代码如下:

1、先注册广播

 <receiver android:name=".upgrade.UpdateRestartReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>//******* 我发现我加其他的没用,只能收到这条
                <action android:name="android.intent.action.PACKAGE_REPLACED" />
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <data android:scheme="package" />
            </intent-filter>
        </receiver>

2.添加广播


public class UpdateRestartReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Logger", "onReceive: "+intent.getAction());
        String packageName = intent.getDataString();
        if (intent.getAction().equals(Intent.ACTION_MY_PACKAGE_REPLACED)) {//接收自己app升级广播            
            Intent intent2 = new Intent(context, LoginActivity.class);//重启app
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent2);
        } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {//接收安装广播
          
            Log.i("Logger",  "onReceive:安装了" + packageName);
            if (packageName.equals("package:" + EpControllerApplication.getInstance().getContext().getPackageName())) {
                /*SystemUtil.reBootDevice();*/
            }
        } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) { //接收卸载广播
            Log.i("Logger",   "onReceive:卸载了" + packageName);
        }

    }

}

注意:测试的时候要升级的app一定是写了广播的app。

记录一下自己所遇见的一些问题,如果有不对的地方,欢迎提出。

如果想写app内部升级请看:https://blog.csdn.net/why_111/article/details/107211511 

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Android 11 中,可以使用 PackageInstaller API 来实现应用程序的静默升级。以下是实现静默升级的步骤: 1. 获取应用程序的 APK 文件。 2. 创建 PackageInstaller.SessionParams 对象。 3. 调用 PackageInstaller.createSession() 方法创建一个会话。 4. 通过会话 ID 打开输出流,并将 APK 文件写入输出流中。 5. 启动会话,等待应用程序安装完成。 以下是一个简单的示例代码: ```java private void installPackageSilently(String apkPath) { // 获取应用程序的 APK 文件 File apkFile = new File(apkPath); // 创建 PackageInstaller.SessionParams 对象 PackageInstaller.SessionParams params = new PackageInstaller.SessionParams( PackageInstaller.SessionParams.MODE_FULL_INSTALL); // 调用 PackageInstaller.createSession() 方法创建一个会话 PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller(); int sessionId = packageInstaller.createSession(params); try { // 通过会话 ID 打开输出流,并将 APK 文件写入输出流中 PackageInstaller.Session session = packageInstaller.openSession(sessionId); OutputStream out = session.openWrite("app", 0, -1); FileInputStream in = new FileInputStream(apkFile); byte[] buffer = new byte[65536]; int c; while ((c = in.read(buffer)) != -1) { out.write(buffer, 0, c); } session.fsync(out); in.close(); out.close(); // 启动会话,等待应用程序安装完成 session.commit(createIntentSender(context, sessionId)); } catch (IOException e) { e.printStackTrace(); } } private IntentSender createIntentSender(Context context, int sessionId) { Intent intent = new Intent(context, getClass()); intent.putExtra(EXTRA_SESSION_ID, sessionId); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); return pendingIntent.getIntentSender(); } ``` 需要注意的是,静默升级需要在系统签名的应用程序中运行,并且需要 android.permission.INSTALL_PACKAGES 权限。另外,如果应用程序已经在运行,则静默升级可能会失败。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值