android adb 静默安装,Android_如何静默安装
Android常用代碼之普通及系統(tǒng)權(quán)限靜默安裝APK
本文主要介紹程序如何安裝apk,包括普通模式安裝和系統(tǒng)權(quán)限靜默安裝。
如果是非系統(tǒng)應(yīng)用請直接查看:Android常用代碼之APK root權(quán)限靜默安裝,查看更完美的解決方案。
1、普通模式安裝,調(diào)用系統(tǒng)Intent,代碼如下:
public static void install(Context context, String filePath) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
2、靜默安裝
如果是非系統(tǒng)應(yīng)用請移步:Android常用代碼之APK root權(quán)限靜默安裝,查看更完美的解決方案。
分為如下三步
(1)、靜默安裝需要系統(tǒng)應(yīng)用安裝權(quán)限,需要在AndroidManifest.xml中添加
Java
1
記得clear啊 一般會出錯提示。
(2)、實現(xiàn)代碼
靜默安裝代碼如下,實際是通過pm install -r 命令安裝。
注意:該函數(shù)最好在新建的線程中運行并通過handler發(fā)送安裝結(jié)果給主線程,否則安裝時間較長會導(dǎo)致ANR。
/**
* install slient
*
* @param context
* @param filePath
* @return 0 means normal, 1 means file not exist, 2 means other exception error
*/
public static int installSlient(Context context, String filePath) {
File file = new File(filePath);
if (filePath == null || filePath.length() == 0 || (file = new File(filePath)) == null || file.length() <= 0
|| !file.exists() || !file.isFile()) {
return 1;
}
String[] args = { "pm", "install", "-r", filePath };
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
BufferedReader succe***esult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
int result;
try {
process = processBuilder.start();
succe***esult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while ((s = succe***esult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
} catch (IOException e) {
e.printStackTrace();
result = 2;
} catch (Exception e) {
e.printStackTrace();
result = 2;
} finally {
try {
if (succe***esult != null) {
succe***esult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
// TODO should add memory is not enough here
if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
result = 0;
} else {
result = 2;
}
Log.d("installSlient", "successMsg:" + successMsg + ", ErrorMsg:" + errorMsg);
return result;
}
返回值0表示安裝成功,1表示文件不存在,2表示其他錯誤。需要更豐富的安裝失敗信息(內(nèi)存不足、解析包出錯)可直接使用PackageUtils.installSlient。
(3) 、獲取系統(tǒng)權(quán)限
完成了上面兩步后,普通方式安裝我們的應(yīng)用仍然無法靜默安裝。需要我們的應(yīng)用獲得系統(tǒng)權(quán)限,編譯應(yīng)用并通過
adb push /system/app/
命令實現(xiàn)安裝,即可擁有系統(tǒng)權(quán)限。
總結(jié)
以上是生活随笔為你收集整理的android adb 静默安装,Android_如何静默安装的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python刷新_如何在python中刷
- 下一篇: 软件设计师c语言算法皇后,软件设计师历年