有時候我們寫 Android APP,需要讓它獲取 ROOT 權限,那麼如何讓 APP 去向系統申請呢?下面提供一個方法,前提是系統是已經 ROOT 權限了,能夠執行能 su 命令。如果不能,可以參考上一篇: 獲取Android系統的ROOT權限 。
- ALPermissionManager 類
package com.allen;
import android.util.Log;
import java.io.DataOutputStream;
public class ALPermissionManager {
/**
* 應用程序運行命令獲取 Root權限,設備必須已破解(獲得ROOT權限)
* @param command 命令:String apkRoot="chmod 777 "+getPackageCodePath(); RootCommand(apkRoot);
* @return 應用程序是/否獲取Root權限
*/
public static boolean RootCommand(String command)
{
Process process = null;
DataOutputStream os = null;
try
{
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e)
{
Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
return false;
} finally
{
try
{
if (os != null)
{
os.close();
}
process.destroy();
} catch (Exception e)
{
}
}
Log.d("*** DEBUG ***", "Root SUC ");
return true;
}
}
- MainActivity
public class MainActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String apkRoot="chmod 777 "+getPackageCodePath();
SystemManager.RootCommand(apkRoot);
}
}