如何在Android系統中判斷裝置是否已root?
在某些情況下,我們不應允許應用程式在已root的裝置上執行,例如支付閘道器。本例演示如何確定應用程式是否在已root的裝置上執行。
步驟 1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟 2 − 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:orientation = "vertical"> <TextView android:id = "@+id/rootFinder" android:layout_margin = "20dp" android:textAlignment = "center" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout>
在上面的程式碼中,我們添加了一個TextView。它包含有關root的資訊。
步驟 3 − 將以下程式碼新增到src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView rootFinder;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
rootFinder = findViewById(R.id.rootFinder);
executeShellCommand("su");
}
private void executeShellCommand(String su) {
Process process = null;
try {
process = Runtime.getRuntime().exec(su);
rootFinder.setText("It is rooted device");
Toast.makeText(MainActivity.this, "It is rooted device", Toast.LENGTH_LONG).show();
} catch (Exception e) {
rootFinder.setText("It is not rooted device");
} finally {
if (process ! = null) {
try {
process.destroy();
} catch (Exception e) { }
}
}
}
}在上面的程式碼中,我們正在測試裝置是否已root,並將文字新增到TextView中。要檢查Android裝置是否已root,請使用以下程式碼:
executeShellCommand("su");
..........................................................................................
private void executeShellCommand(String su) {
Process process = null;
try {
process = Runtime.getRuntime().exec(su);
rootFinder.setText("It is rooted device");
Toast.makeText(MainActivity.this, "It is rooted device", Toast.LENGTH_LONG).show();
} catch (Exception e) {
rootFinder.setText("It is not rooted device");
} finally {
if (process ! = null) {
try {
process.destroy();
} catch (Exception e) { }
}
}
}讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要在Android Studio中執行該應用程式,請開啟您專案中的一個活動檔案,然後單擊工具欄中的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:

以上結果顯示,我們的裝置尚未root。
點選這裡下載專案程式碼
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP