静默安装/卸载app+重启设备代码

我要说的这种方法是要将自己的app升级为系统应用,才可以操作,具体如何升级为系统应用可以查看将app应用升级为系统应用这篇博客

1、添加安装/卸载/重启设备的系统权限

<!--    重启系统权限-->
    <uses-permission android:name="android.permission.REBOOT"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions" />
	<uses-permission android:name="android.permission.DELETE_PACKAGES"
        tools:ignore="ProtectedPermissions" />

2、安装apk

/**
     * @param filepathApk 文件路径
     */
    public static void installPackage(String filepathApk) {
        try {
            PackageInstaller pi = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                pi = context.getPackageManager().getPackageInstaller();
            }
            //给定模式,创建新的参数,创建新安装会话,返回唯一 Id
            int sessionId= 0;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                sessionId = pi.createSession(new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL));
            }
            //打开现有会话,主动执行工作
            PackageInstaller.Session session = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                session = pi.openSession(sessionId);
            }
            long sizeBytes = 0;
            final File file = new File(filepathApk);
            if (file.isFile()) {
                sizeBytes = file.length();
            }
            InputStream in = null;
            OutputStream out = null;
            in = new FileInputStream(filepathApk);
            //打开一个流,将一个APK文件写入会话
            //指定有效长度系统将预先分配底层磁盘空间以优化磁盘上的放置
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                out = session.openWrite("app_store_session", 0, sizeBytes);
            }
            int total = 0;
            byte[] buffer = new byte[65536];
            int len;
            while ((len= in.read(buffer)) != -1) {
                total += len;
                out.write(buffer, 0, len);
            }
            //根据需要调用,用来确保字节已保留到磁盘
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                session.fsync(out);
            }
            in.close();
            out.close();
            LogUtils.d("Success: streamed apk " + total + " bytes");
            PendingIntent broadCastTest = PendingIntent.getBroadcast(context, sessionId, new Intent(ACTION_INSTALL_SUCCESS), PendingIntent.FLAG_UPDATE_CURRENT);
            //提交之前必须关闭所有流
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                session.commit(broadCastTest.getIntentSender());
            }
            session.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

ACTION_INSTALL_SUCCESS是要接收的广播name

<!--     注册安装完成后的广播   -->
<receiver android:name="com.wxcy.guangming.receiver.InstallSuccessReceiver"
            android:exported="true">
            <intent-filter >
                <action android:name="action.install.success" />

                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>
public class InstallSuccessReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("action.install.success")) {
            Intent intent1=new Intent(context, MainActivity.class);
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent1);
            LogUtils.d("安装完成");
        }
    }
}

3、卸载apk

**
     * @param packageName 应用包名
     */
    public static void uninstallPackage(String packageName) {
        Intent intent = new Intent(context, context.getClass());
        PendingIntent sender = PendingIntent.getActivity(context, 0, intent, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            PackageInstaller mPackageInstaller = context.getPackageManager().getPackageInstaller();
            mPackageInstaller.uninstall(packageName, sender.getIntentSender());
        }
    }

4、重启设备

/**
     * 重启设备
     */
    public static void rebootSystem() {
        PowerManager manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        manager.reboot("重新启动系统");
    }

5、获得当前包的versionCode

/***
     * packageInfo.versionName
     * packageInfo.versionCode
     */
    //获得包信息
    public static PackageInfo getPackageInfo(){
        //获取packageManager实例
        PackageManager packageManager = context.getPackageManager();
        // 获取包名
        String packageName = context.getPackageName();
        int flag = 0;
        PackageInfo packageInfo = null;

        // 获取packageInfo
        try {
            packageInfo = packageManager.getPackageInfo(packageName, flag);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值