android UiAutomator如何利用adb install和adb uninstall實現安裝和卸載

本人在看android UiAutomator快速調試的代碼時,突然想到一個問題,既然能實現運行cmd命令,那寫一個能實現快速調試安裝和卸載的方法就挺好的,方便快捷,一鍵實現自己想要的功能。經過不斷嘗試,基本需求實現了。分享出來,如果不對的地方,還請指正。

在包下新建一個UpdateApp的類,裏面的代碼如下:

package student;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


import android.widget.VideoView;


public class UpdateApp {
public static void main(String[] args) {
String packagename="", filename="";
new UpdateApp(packagename, filename, false);


}
//通過key控制卸載安裝還是直接卸載
public UpdateApp(String classname, String filename, boolean key) {
if (key) {
uninstall(classname);
install(filename);
}else{
uninstall(classname);
}

}
//安裝
public void install(String filename) {
execCmd("cmd /c adb install c:\\users\\user\\Desktop\\"+filename+".apk");
System.out.println("安裝成功!");
}
//卸載
public void uninstall(String classname) {
execCmd("cmd /c adb uninstall "+classname);
System.out.println("卸載成功!");
}
public void execCmd(String cmd) {
System.out.println("----execCmd:  " + cmd);
try {
Process p = Runtime.getRuntime().exec(cmd);
// 正確輸出流
InputStream input = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = "";
while ((line = reader.readLine()) != null) {
//因爲安裝過程中,會不斷輸出發送百分比,這裏就只輸出“Success”
if(line.equalsIgnoreCase("Success")){
System.out.println(line);
}
//雖然上一部屏蔽了一些信息,但還是會寫入log文件中
saveToFile(line, "runlog.log", false);
}
// 錯誤輸出流,這裏就不屏蔽任何錯誤信息了
InputStream errorInput = p.getErrorStream();
BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorInput));
String eline = "";
while ((eline = errorReader.readLine()) != null) {
System.out.println(eline);
saveToFile(eline, "runlog.log", false);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveToFile(String text, String path, boolean isClose) {
File file = new File("runlog.log");
BufferedWriter bf = null;
try {
FileOutputStream outputStream = new FileOutputStream(file, true);
OutputStreamWriter outWriter = new OutputStreamWriter(outputStream);
bf = new BufferedWriter(outWriter);
bf.append(text);
bf.newLine();
bf.flush();


if (isClose) {
bf.close();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


}
}


在我的測試類中添加一個main方法即可:

public static void main(String[] args){
//最後一個參數,true表示先卸載再安裝,false表示只卸載
new UpdateApp("com.dianzhi.student", "1", true);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章