1. 程式人生 > >檢測Android手機是否具有root許可權和靜默安裝

檢測Android手機是否具有root許可權和靜默安裝

執行靜默安裝時,需要向手機申請獲取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;  
    }  
}  
許可權:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 


轉自【http://www.open-open.com/lib/view/open1409191402244.html】