如何在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