最近在做免用户点击安装apk,简单的记录下,多数应用在广告屏,商户屏,以及我们常见的贩卖机
思路:我们创建两个app,一个是app的主程序,里面做后台判断更新,下载apk,始终运行在前台,另一个是app更新程序,当主程序需要更新的时候,会主动调用cmd,两个app通过AIDL连接,废话不多说,上代码
/**
* 下载监听器
*/
private JsDownloadListener mDownloadListener = new JsDownloadListener() {
@Override
public void onStartDownload() {
LogUtils.d("by ygli. onStartDownload.");
}
@Override
public void onProgress(int progress) {
LogUtils.d("by ygli. onProgress. progress:" + progress);
}
@Override
public void onFinishDownload() {
LogUtils.d("by ygli. onFinishDownload. ");
try {
//重点在这里
if (aidlService != null) {
aidlService.install(LOCAL_PATH);
LogUtils.e("aidlService != null----");
} else {
LogUtils.e("Intent intent = new Intent();----");
isUpdate = true;
Intent intent = new Intent();
//两个应用aidl包名必须保持一致
intent.setAction("com.test.update.IUpdateService");
intent.setPackage("com.test.ados.update");
bindService(intent, new MyConnection(), BIND_AUTO_CREATE);
}
} catch (RemoteException e) {
e.printStackTrace();
}
isUpdataing = false;
}
@Override
public void onFail(String errorInfo) {
LogUtils.d("by ygli. onFail. errorInfo:" + errorInfo);
isUpdataing = false;
}
};
public class MyConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
aidlService = IUpdateService.Stub.asInterface(service);
if (isUpdate) {
try {
isUpdate = false;
aidlService.install(LOCAL_PATH);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
if (aidlService != null) {
aidlService = null;
}
}
}
/**
*连接两个app aidl中的方法
**/
interface IUpdateService {
void install(String path);
}
/**
*启动cmd关键方法(可以创建一个cmd工具类)
*执行linux命令但不关注结果输出
**/
public static int execRootCmdSilent(String paramString) {
Object localObject = -1;
try {
Process localProcess = Runtime.getRuntime().exec("su");
localObject = localProcess.getOutputStream();
DataOutputStream localDataOutputStream = new DataOutputStream((OutputStream) localObject);
String str = String.valueOf(paramString);
localObject = str + "\n";
localDataOutputStream.writeBytes((String) localObject);
localDataOutputStream.flush();
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localProcess.waitFor();
localObject = localProcess.exitValue();
} catch (Exception localException) {
localException.printStackTrace();
}
return (int) localObject;
}
LogUtils.d("install begin. path:" + path);
boolean isRoot = RootCmd.haveRoot();
int result1 = RootCmd.execRootCmdSilent("chmod 777 /data/local");
LogUtils.d("install end. isRoot:" + isRoot + ", result1:" + result1);
//path为apk下载地址
int result2 = RootCmd.execRootCmdSilent("pm install -r -g " + path);
int result3 = RootCmd.execRootCmdSilent("am start -n 包名下主程序入口");