Giới thiệu
Một số ứng dụng (đặc biệt là ngân hàng, thanh toán) cần kiểm tra thiết bị có bị root hay không để đảm bảo bảo mật. Ví dụ này minh họa cách phát hiện thiết bị root bằng cách thử thực thi lệnh su.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (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>
Bước 3: Logic kiểm tra root (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 command) {
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
rootFinder.setText("Thiết bị ĐÃ root");
Toast.makeText(MainActivity.this, "Thiết bị ĐÃ root", Toast.LENGTH_LONG).show();
} catch (Exception e) {
rootFinder.setText("Thiết bị CHƯA root");
} finally {
if (process != null) {
try {
process.destroy();
} catch (Exception e) { }
}
}
}
}
Giải thích cơ chế
executeShellCommand("su");
su(Switch User / Super User): Lệnh yêu cầu quyền root trên Linux/AndroidRuntime.getRuntime().exec("su"): Thử thực thi lệnh su- Nếu thành công (không throw exception) → Thiết bị đã root
- Nếu thất bại (throw SecurityException/IOException) → Thiết bị chưa root
process.destroy(): Giải phóng tài nguyên process
⚠️ Lưu ý bảo mật: Phương pháp này cơ bản. Các ứng dụng bảo mật cao nên kết hợp nhiều phương pháp: kiểm tra file
/system/bin/su, /system/xbin/su, app SuperSU/Magisk, SafetyNet Attestation API, Play Integrity API.
Chạy ứng dụng
Chạy app trên thiết bị thật. TextView sẽ hiển thị "Thiết bị ĐÃ root" hoặc "Thiết bị CHƯA root" tùy theo trạng thái thiết bị.