检测Android手机是否具有root权限和静默安装

jopen 10年前

执行静默安装时,需要向手机申请获取root权限,如果手机具有root权限,则可以完成安装。代码如下:

MainActivity:

</div>
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;        }    }  
</div>

权限:

</div>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
</div>