ตัวอย่าง: การตรวจสอบอุปกรณ์ที่ Root แล้ว
ในบางกรณี เช่น ระบบชำระเงิน เราไม่ควรให้แอปทำงานบนอุปกรณ์ที่ Root แล้ว ตัวอย่างนี้สาธิตวิธีตรวจสอบว่าเป็นอุปกรณ์ที่ Root แล้วหรือไม่
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็น
ขั้นตอนที่ 2: จัดการ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://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: เขียนโค้ด Java (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("เป็นอุปกรณ์ที่ Root แล้ว");
Toast.makeText(MainActivity.this, "เป็นอุปกรณ์ที่ Root แล้ว", Toast.LENGTH_LONG).show();
} catch (Exception e) {
rootFinder.setText("ไม่ใช่อุปกรณ์ที่ Root");
} finally {
if (process != null) {
try {
process.destroy();
} catch (Exception e) { }
}
}
}
}
โค้ดสำคัญ: การตรวจสอบ Root ผ่านคำสั่ง Shell
executeShellCommand("su");
...
private void executeShellCommand(String su) {
Process process = null;
try {
process = Runtime.getRuntime().exec(su);
rootFinder.setText("เป็นอุปกรณ์ที่ Root แล้ว");
Toast.makeText(MainActivity.this, "เป็นอุปกรณ์ที่ Root แล้ว", Toast.LENGTH_LONG).show();
} catch (Exception e) {
rootFinder.setText("ไม่ใช่อุปกรณ์ที่ Root");
} finally {
if (process != null) {
try {
process.destroy();
} catch (Exception e) { }
}
}
}
วิธีนี้พยายามรันคำสั่ง su (Super User) หากสำเร็จ แสดงว่าเป็นอุปกรณ์ที่ Root แล้ว หากล้มเหลว (throw Exception) แสดงว่าไม่ได้ Root
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอ

ในผลลัพธ์ แสดงว่าอุปกรณ์ทดสอบยังไม่ได้ Root