執行靜默安裝時,需要向手機申請獲取root許可權,如果手機具有root許可權,則可以完成安裝。代碼如下:

MainActivity:

 
import java.io.DataOutputStream;
import java.io.File;
import java.io.OutputStream;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {
private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 笔者手机上的apk路径
String apkName = Environment.getExternalStorageDirectory().toString()
+ File.separator + "police.apk";
Log.e(TAG, "root = " + haveRoot("pm install -r " + apkName));
}

/**
* 检测是否具体root权限
*
* @param cmd
* @return
*/
private boolean haveRoot(String cmd) {
int i = execRootCmdSilent(cmd);
if (i != -1) {
return true;
}
return false;
}

/**
* 执行静默安装
*
* @param paramString
* @return
*/
private int execRootCmdSilent(String paramString) {
int result = -1;
try {
Process localProcess = Runtime.getRuntime().exec("su");
OutputStream os = localProcess.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeBytes(paramString + "\n");
dos.flush();
dos.writeBytes("exit\n");
dos.flush();
localProcess.waitFor();
result = localProcess.exitValue();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
权限:

?
1
2
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

創作者介紹

資訊園

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()