安卓app实现静默安装和卸载

下载app采用的是谷歌推出的DownloadManager下载的 有借鉴别人的地方 自己整理了一下然后增加了静默安装的方法
要静默安装必须root手机哦 如果没有root手机只能使用意图安装了install()
老规矩 少废话 上代码
下边会付上调用方法

/**
* Created by 海边两个人的浪漫 on 2018/4/3.
*/

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;

public class DownLoadUtil {
private Context context;
private String notificationTitle;
private String notificationDescription;
private DownloadManager downLoadManager;
private long downloadId;

public void downLoad(String url, String appPath, String appname) {
    Request request = new Request(Uri.parse(url));
    //设置状态栏中显示Notification
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    if (!TextUtils.isEmpty(getNotificationTitle())) {
        request.setTitle(getNotificationTitle());
    }
    if (!TextUtils.isEmpty(getNotificationDescription())) {
        request.setDescription(getNotificationDescription());
    }
    //设置可用的网络类型
    request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
    //不显示下载界面
    request.setVisibleInDownloadsUi(false);

    //创建文件的下载路径
    File folder = Environment.getExternalStoragePublicDirectory(appPath);
    if (!folder.exists() || !folder.isDirectory()) {
        folder.mkdirs();
    }
    //指定下载的路径为和上面创建的路径相同
    request.setDestinationInExternalPublicDir(appPath, appname);

    //设置文件类型
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
    request.setMimeType(mimeString);
    //将请求加入请求队列会 downLoadManager会自动调用对应的服务执行者个请求
    downloadId = downLoadManager.enqueue(request);
}

/**
 * 描述: 安装
 */
public static boolean install(String apkPath, String appname, Context context) {
    String PATH = Environment.getExternalStorageDirectory().getPath() + apkPath;
    // 先判断手机是否有root权限
    if (hasRootPerssion()) {
        // 有root权限,利用静默安装实现
        LogUtil.i("开始安装");
        return clientInstall(PATH);

// return install(PATH);
} else {
// 没有root权限,利用意图进行安装
install(context, PATH);
return true;
}
}

//apk的安装 方法
public static boolean install(Context context, String appPath) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    File file = new File(appPath);
    if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
        intent.setDataAndType(Uri.parse("file://" + appPath), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return true;
    }
    return false;
}

/**
 * 描述: 卸载
 */
public static boolean uninstall(String packageName, Context context) {
    if (hasRootPerssion()) {
        // 有root权限,利用静默卸载实现
        return clientUninstall(packageName);
    } else {
        Uri packageURI = Uri.parse("package:" + packageName);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(uninstallIntent);
        return true;
    }
}

/**
 * 判断手机是否有root权限
 */
public static boolean hasRootPerssion() {
    PrintWriter PrintWriter = null;
    Process process = null;
    try {
        process = Runtime.getRuntime().exec("su");
        PrintWriter = new PrintWriter(process.getOutputStream());
        PrintWriter.flush();
        PrintWriter.close();
        int value = process.waitFor();
        return returnResult(value);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return false;
}

/**
 * 静默安装
 */
public static boolean clientInstall(String apkPath) {
    PrintWriter PrintWriter = null;
    Process process = null;
    try {
        LogUtil.i("开始安装+++");
        process = Runtime.getRuntime().exec("su");
        PrintWriter = new PrintWriter(process.getOutputStream());
        PrintWriter.println("chmod 777 " + apkPath);
        PrintWriter.println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib");
        PrintWriter.println("pm install -r " + apkPath);

// PrintWriter.println(“exit”);
LogUtil.i(“开始安装++++++++++++”);
PrintWriter.flush();
PrintWriter.close();
int value = process.waitFor();
LogUtil.i(“开始安装+++————–”);
return returnResult(value);
} catch (Exception e) {
e.printStackTrace();
LogUtil.i(“安装异常+++————–”+e);
} finally {
if (process != null) {
process.destroy();
LogUtil.i(“安装完成+++————–”);
}
}
return false;
}

/**
 * 静默卸载
 */
public static boolean clientUninstall(String packageName) {
    PrintWriter PrintWriter = null;
    Process process = null;
    try {
        process = Runtime.getRuntime().exec("su");
        PrintWriter = new PrintWriter(process.getOutputStream());
        PrintWriter.println("LD_LIBRARY_PATH=/vendor/lib:/system/lib ");
        PrintWriter.println("pm uninstall " + packageName);
        PrintWriter.flush();
        PrintWriter.close();
        int value = process.waitFor();
        return returnResult(value);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return false;
}

/**
 * 启动app
 * com.exmaple.client/.MainActivity
 * com.exmaple.client/com.exmaple.client.MainActivity
 */
public static boolean startApp(String packageName, String activityName) {
    boolean isSuccess = false;
    String cmd = "am start -n " + packageName + "/" + activityName + " \n";
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(cmd);
        int value = process.waitFor();
        return returnResult(value);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return isSuccess;
}

/**
 * 将文件复制到system/app 目录
 *
 * @param apkPath 特别注意格式:该路径不能是:/storage/emulated/0/app/QDemoTest4.apk 需要是:/sdcard/app/QDemoTest4.apk
 * @return
 */
public static boolean copy2SystemApp(String apkPath) {
    PrintWriter PrintWriter = null;
    Process process = null;
    String appName = "chetou.apk", cmd;

    try {
        process = Runtime.getRuntime().exec("su");
        PrintWriter = new PrintWriter(process.getOutputStream());
        cmd = "mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system";
        Log.e("copy2SystemApp", cmd);
        PrintWriter.println(cmd);

        cmd = "cat " + apkPath + " > /system/app/" + appName;
        Log.e("copy2SystemApp", cmd);
        PrintWriter.println(cmd);

        cmd = "chmod 777 /system/app/" + appName + " -R";
        Log.e("copy2SystemApp", cmd);
        PrintWriter.println(cmd);

        cmd = "mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system";
        Log.e("copy2SystemApp", cmd);
        PrintWriter.println(cmd);
        PrintWriter.println("reboot");  //重启
        PrintWriter.println("exit");
        PrintWriter.flush();
        PrintWriter.close();
        int value = process.waitFor();
        return returnResult(value);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return false;
}

private static boolean returnResult(int value) {
    // 代表成功
    if (value == 0) {
        return true;
    } else if (value == 1) { // 失败
        return false;
    } else { // 未知情况
        return false;
    }
}

public static boolean install(String apkPath) {
    boolean result = false;
    DataOutputStream dataOutputStream = null;
    BufferedReader errorStream = null;
    try {
        // 申请su权限
        Process process = Runtime.getRuntime().exec("su");
        dataOutputStream = new DataOutputStream(process.getOutputStream());
        // 执行pm install命令
        String command = "pm install -r " + apkPath + "\n";
        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.d("TAG", "install msg is " + msg);
        // 如果执行结果中包含Failure字样就认为是安装失败,否则就认为安装成功
        if (!msg.contains("Failure")) {
            result = true;
        }
    } catch (Exception e) {
        Log.e("TAG", e.getMessage(), e);
    } finally {
        try {
            if (dataOutputStream != null) {
                dataOutputStream.close();
            }
            if (errorStream != null) {
                errorStream.close();
            }
        } catch (IOException e) {
            Log.e("TAG", e.getMessage(), e);
        }
    }
    return result;
}
public String getNotificationTitle() {
    return notificationTitle;
}

public void setNotificationTitle(String notificationTitle) {
    this.notificationTitle = notificationTitle;
}

public String getNotificationDescription() {
    return notificationDescription;
}

public void setNotificationDescription(String notificationDescription) {
    this.notificationDescription = notificationDescription;
}

public DownLoadUtil(Context context) {
    this.context = context;
    downLoadManager = (DownloadManager) this.context
            .getSystemService(Context.DOWNLOAD_SERVICE);
}

}
最后附上调用方法:
DownLoadUtil downLoadUtil = new DownLoadUtil(MainActivity.this);
downLoadUtil.downLoad(“你的apk地址”, DOWNLOAD_FOLDER_NAME, DOWNLOAD_APP_NAME);
剩下两个参数 一个是apk保存地址 最后一个是apk的名字
如果你觉得此下载比较麻烦 没关系 okhttp可以搞定 有进度条的哟 附上okhttp的地址 有需要的朋友可以看一下
https://blog.csdn.net/qq_34656823/article/details/80017656

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值