参考
1、Android静默安装和静默卸载
2、Android真正的静默安装(android7.0静默安装)
场景
各种以android硬件平台为基础的【公示屏】、【广告屏】等等,虽然很少有升级,但是不可避免的会遇到,而此类APP的使用场景,一般没人会去帮助你版本更新,点击安装,故而需要:静默安装。
一、普通升级(可略过)
1、确认安装包是否存在,并可读写
2、隐示启动:action和data的schema来控制弹出安装工具类APP,然后点击安装...
3、升级完:BootReceiver 监听到Intent.ACTION_PACKAGE_REPLACED,然后自启动
/**
* 普通升级
* 1、确认安装包是否存在,并可读写
* 2、隐示启动:action和data的schema来控制弹出安装工具类APP,然后点击安装...
* 3、升级完:BootReceiver 监听到Intent.ACTION_PACKAGE_REPLACED,然后自启动
*
* vivo弹不出升级安装框...
* */
private void installApk(String apkPath,String apkName)
{
LogUtil.i("installApk():-----------------");
File apkfile = new File(apkPath, apkName);
if (!apkfile.exists())
{
LogUtil.e("尚无APK文件");
return;
}
//add permission
String[] command = {"chmod", "777", apkfile.getPath() };
ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.start();
} catch (IOException e) {
LogUtil.e("ProcessBuilder IOException="+e.getMessage());
e.printStackTrace();
}
Intent i = new Intent(Intent.ACTION_VIEW);
//安装完成自动打开
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 判断版本大于等于7.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
i.setDataAndType(FileProvider.getUriForFile(this, APP_File_Provider,apkfile),
"application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//临时权限
}else{
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
"application/vnd.android.package-archive");
}
this.startActivity(i);
}
二、静默升级(系统厂家提供)--- 强烈建议
静默安装apk接口,无需开放root,也无需system权限。
Intent cmdIntent = new Intent("com.balabalabalbalbalba.syscmd"); //系统厂家给的action命令
cmdIntent.putExtra("cmd", "appinstall");
cmdIntent.putExtra("parm", "xxxx/xxxx");//这里是apk的路径
sendBroadcast(cmdIntent);
三、静默升级+自启动(必须Root,必须Root,必须Root!)
1、BootReceiver.java
/**
* 程序卸载,安装,更新的广播监听器
* */
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String packageName = intent.getDataString().substring(8);
LogUtil.d("BootReceiver onReceive():接收到Intent.getAction() = "+intent.getAction()+" , 包名 = "+intent.getDataString());
/**
* 接收安装广播
* android.intent.action.PACKAGE_ADDED
* */
if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
LogUtil.d("BootReceiver onReceive():安装了:" + packageName + "包名的程序");
}
/**
* 接收卸载广播
* android.intent.action.PACKAGE_REMOVED
* */
if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
LogUtil.d("BootReceiver onReceive():卸载了:" + packageName + "包名的程序");
}
/**
* 接收更新广播
* android.intent.action.PACKAGE_REPLACED
* */
if(action.equals(Intent.ACTION_PACKAGE_REPLACED)){
LogUtil.d("BootReceiver onReceive():更新了:" + packageName + "包名的程序,context.getPackageName()="+context.getPackageName());
//更新的软件包名是否和我的工程一致
if(packageName.equals(context.getPackageName())){
//更新完后打开
Intent it = new Intent();
it.setClassName(packageName, packageName + ".MainActivity"); //启动类
it.setAction("android.intent.action.MAIN"); //首个启动类action
it.addCategory("android.intent.category.LAUNCHER"); //放入程序列表
//it.addCategory("android.intent.category.HOME"); //作为桌面,Home键打开,可做启动默认程序
it.addCategory("android.intent.category.DEFAULT"); //隐式打开,如果没main可有,如果main可有可无
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(it);
}
}
/**
* 接收重启广播
* android.intent.action.PACKAGE_REPLACED
* */
if(action.equals(Intent.ACTION_PACKAGE_RESTARTED)){
LogUtil.d("BootReceiver onReceive():重启了:" + packageName + "包名的程序");
}
/**
* 接收开机广播
* android.intent.action.BOOT_COMPLETED
* */
if(action.equals(Intent.ACTION_BOOT_COMPLETED)){
LogUtil.d("BootReceiver onReceive():仪器开机,开启了:" + packageName + "包名的程序");
}
}
}
2、静默安装:主体代码(这里没用thread去线程安装,可优化的部分...)
- 检查是否有root权限,没有的话授予
- 确认安装包是否存在,并可读写
- 用Runtime.getRuntime().exec(“su”)后进行root执行cmd进行安装
- 安装成功后也考runtime执行cmd进行启动,BootReceiver会接收,并打开应用
/**
* 静默升级:这里是同步的,正式要考虑异步thread去做这个事情!!!
* 1、检查系统是否有root权限
* 2、检查APP是否有root权限
* 3、确认安装包是否存在,并可读写
* 4、root下安装apk
* 5、root下通知开启apk
*
* 注意:
* 在当前的activity必要有个screenOrientation方向,否则的话runtime运行会把询问授予root权限的框给占用掉
* */
private void sinlenceInstallApk(String apkPath,String apkName){
LogUtil.i("sinlenceInstallApk():-----------------");
//1
if(!SystemCtrlUtil.sysHasRootPerssion()){
LogUtil.e("系统尚无Root权限");
Toast.makeText(this,"系统尚无Root权限",Toast.LENGTH_SHORT).show();
return;
}
LogUtil.i("系统有Root权限");
//2
// if(!SystemCtrlUtil.appHasRootPerssion(this)){
// LogUtil.e("APP尚无Root权限");
// Toast.makeText(this,"APP尚无Root权限",Toast.LENGTH_SHORT).show();
// return;
// }
// LogUtil.i("APP有Root权限");
//3
File apkfile = new File(apkPath, apkName);
if (!apkfile.exists())
{
LogUtil.e("尚无APK文件");
return;
}
//4、静默安装
if(SystemCtrlUtil.rootSlienceInstallApk(apkPath+"/"+apkName)){
LogUtil.d("静默安装成功");
//5、执行此命令后:BootReceiver 监听到Intent.ACTION_PACKAGE_REPLACED,然后自启动
if(SystemCtrlUtil.rootStartApk("com.wujn.sinceupdat.sinceupdate", "MainActivity")){
LogUtil.d("静默安装后启动APP成功");
}else{
LogUtil.e("静默安装后启动APP失败!!!");
Toast.makeText(this,"静默安装后启动APP失败!!!",Toast.LENGTH_SHORT).show();
}
}else{
LogUtil.e("静默安装失败!!!");
Toast.makeText(this,"静默安装失败!!!",Toast.LENGTH_SHORT).show();
}
}
3、工具类
/**
* Created by wujn on 2018/12/13.
* Version : v1.0
* Function: 系统级别的控制,包括root
*
* 参考:https://blog.csdn.net/andywuchuanlong/article/details/44150317
*/
public class SystemCtrlUtil {
/**
* root下静默安装
* */
public static boolean rootSlienceInstallApk(String apkPath){
PrintWriter PrintWriter = null;
Process process = null;
try {
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");
PrintWriter.flush();
PrintWriter.close();
int value = process.waitFor();
return returnResult(value);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(process!=null){
process.destroy();
}
}
return false;
}
/**
* root下启动apk
* */
public static boolean rootStartApk(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;
}
/**
* root下静默删除
* */
public static boolean rootSlienceUninstallApk(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;
}
/**
* 判断手机是否有root权限
*/
public static boolean sysHasRootPerssion(){
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;
}
/**
* root下执行cmd的返回值
* */
private static boolean returnResult(int value){
// 代表成功
if (value == 0) {
return true;
} else if (value == 1) { // 失败
return false;
} else { // 未知情况
return false;
}
}
/**
* 判断app是否有root权限
*/
public static boolean appHasRootPerssion(Context context){
return RootCommand("chmod 777 "+context.getPackageCodePath());
}
/**
* 应用程序运行命令获取 Root权限,设备必须已破解(获得ROOT权限)
* @param command 命令:String apkRoot="chmod 777 "+getPackageCodePath(); RootCommand(apkRoot);
* @return 应用程序是/否获取Root权限
*/
public static boolean RootCommand(String command)
{
Process process = null;
DataOutputStream os = null;
try
{
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
return returnResult(process.waitFor());
} catch (Exception e)
{
Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
return false;
} finally
{
try
{
if (os != null)
{
os.close();
}
process.destroy();
} catch (Exception e)
{
}
}
}
}