iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 1
0
Mobile Development

Android踩過的坑系列 第 1

檢查手機是否越獄(ROOT)

  • 分享至 

  • xImage
  •  

有些App會要求執行時先檢查該裝置是否有Root權限,尤其是資安要求較高的應用
這邊紀錄一些檢查的方法

private boolean checkSuperUserDir(){
for(String pathDir : System.getenv("PATH").split(":")){
if(new File(pathDir,"su").exists()){
return true;
}
}
return false;
}
這邊是用System.getenv()來列出環境變數中的路徑,並用:冒號來做分段,
接著用檔案夾的操作new File(pathDir,"su").exists()來檢查是否有命名su的檔案
參數1(String: pathDir)此處填寫的是使用System.getenv找出的路徑
參數2(String: "su")此處填寫的是檔案名
使用new File定義出檔案的位置之後,最後用方法.exists()來確定檔案是否存在。

接著寫判斷是否為Root的部分

private boolean isRoot(){
if(checkSuperUserDir){
Process process = null;
try{
process= Runtime.getRuntime().exec(new String[]{"su","-c","id"});
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = bufferedReader.readLine();
if(!TextUtils.isEmpty(output) && output.toLowerCase().contains("uid=0")){
return true;
}
}catch{
e.printStackTrace();
}finally{
if (process != null)process.destroy();
}
}
return false;
}
在isRoot()的第一行就先判斷在裝置中是否有SuperUser的資料夾,有的話才繼續執行,
Runtime.getRuntime().exec(new String[]{"su","-c","id"})
這一行是是在取得使用者的ID,newString[]{}是在組成要執行的指令,
完整指令為su -c id
su:取得root權限
-c:執行完關閉
id:列出使用者id

Runtime.getRuntime().exec執行後使用BufferedReader讀出內容,
先用!TextUtils.isEmpty來確保讀出的內容不為null或空值,
接著用.toLowerCase()將內容變為小寫,接著用.contains("uid=0")檢查,
在系統中uid=0表示為SuperUser也就是Root權限所有,
所以當contains回傳true則表示該裝置為Root過的。


下一篇
確保App在合理的使用環境中執行
系列文
Android踩過的坑2
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言