การดึงชื่อรุ่นอุปกรณ์ (Device Model) ใน Android ด้วยโค้ด
ตัวอย่างนี้แสดงวิธีอ่านชื่อรุ่นโทรศัพท์ (Phone Model) เช่น "SM-G973F", "Pixel 5" ผ่านคลาส android.os.Build และแสดงผลบนหน้าจอ
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → กรอกรายละเอียด → Finish
ขั้นตอนที่ 2: จัดหน้าตา - res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
tools:context=".MainActivity">
<TextView
android:gravity="center"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="18sp" />
</RelativeLayout>
ขั้นตอนที่ 3: โค้ดหลัก - src/MainActivity.java
package app.tutorialspoint.com.sample;
import android.os.Build;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(getPhoneModel());
}
private String getPhoneModel() {
return Build.MODEL;
}
}
ขั้นตอนที่ 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ข้อมูลเพิ่มเติมจาก Build Class
คลาส Build มีฟิลด์อื่นๆ ที่มีประโยชน์:
| ฟิลด์ | คำอธิบาย |
|---|---|
| Build.MODEL | ชื่อรุ่นอุปกรณ์ (เช่น SM-G973F) |
| Build.MANUFACTURER | ผู้ผลิต (เช่น samsung, Google) |
| Build.BRAND | แบรนด์ (เช่น Samsung, google) |
| Build.DEVICE | ชื่อโค้ดอุปกรณ์ (เช่น beyond1) |
| Build.PRODUCT | ชื่อผลิตภัณฑ์ |
| Build.VERSION.RELEASE | เวอร์ชัน Android (เช่น 11, 12) |
| Build.VERSION.SDK_INT | API Level (เช่น 30, 31) |
| Build.FINGERPRINT | ลายนิ้วมือ Build 完整 |
ตัวอย่างการใช้งานเพิ่มเติม
String deviceInfo = "Model: " + Build.MODEL + "\n" +
"Manufacturer: " + Build.MANUFACTURER + "\n" +
"Brand: " + Build.BRAND + "\n" +
"Android Version: " + Build.VERSION.RELEASE + "\n" +
"API Level: " + Build.VERSION.SDK_INT;
การทดสอบ
รันบนอุปกรณ์จริง จะแสดงชื่อรุ่นโทรศัพท์ที่ TextView ตรงกลางหน้าจอ