บทนำ
ตัวอย่างนี้แสดงวิธีการตรวจสอบว่าผู้ใช้ปัจจุบัน (Current User) บนอุปกรณ์ Android เป็น "ผู้ใช้ระบบ" (System User) หรือไม่ โดยใช้คลาส UserManager และเมธอด isSystemUser() ซึ่งพร้อมใช้งานตั้งแต่ Android 7.0 (API Level 24) ขึ้นไป
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่ใน Android Studio
เปิด Android Studio → File → New Project → เลือก "Empty Activity" → กรอกรายละเอียดโปรเจกต์ → Finish
ขั้นตอนที่ 2: จัดการหน้าจอ (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp" />
</LinearLayout>
ใช้ TextView เพื่อแสดงผลสถานะของผู้ใช้
ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.os.UserManager;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
// เรียกใช้ UserManager เพื่อตรวจสอบสถานะผู้ใช้
UserManager manager = (UserManager) getSystemService(USER_SERVICE);
// isSystemUser() จะคืนค่า true หากเป็นผู้ใช้ระบบ (Primary User)
textView.setText("" + manager.isSystemUser());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
ขั้นตอนที่ 4: ทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ → กดปุ่ม Run ใน Android Studio → เลือกอุปกรณ์ → ดูผลลัพธ์บนหน้าจออุปกรณ์

หมายเหตุเพิ่มเติม
- เมธอด
isSystemUser()ต้องการ API Level 24 (Android 7.0 Nougat) ขึ้นไป - ผู้ใช้ระบบ (System User) คือผู้ใช้หลักของอุปกรณ์ (Primary User) ที่สร้างขึ้นตอนตั้งค่าครั้งแรก
- หากอุปกรณ์รองรับหลายผู้ใช้ (Multi-user) ผู้ใช้รอง (Secondary User) จะคืนค่า
false