บทนำ
ตัวอย่างนี้สาธิตวิธีดึงที่อยู่ MAC Address ของอุปกรณ์ Bluetooth ปัจจุบันโดยใช้ BluetoothManager และ getAddress()
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (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>
ขั้นตอนที่ 3: โค้ดหลัก (MainActivity.java)
package com.example.myapplication;
import android.bluetooth.BluetoothManager;
import android.os.Build;
import android.os.Bundle;
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);
final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
// ดึง MAC Address ของ Bluetooth Adapter
textView.setText(manager.getAdapter().getAddress());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
ขั้นตอนที่ 4: AndroidManifest.xml - Permission
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ผลลัพธ์

ข้อควรระวังสำคัญ
- Android 6.0 (API 23) ขึ้นไป: การเข้าถึง MAC Address จำกัดแล้ว สำหรับ Wi-Fi และ Bluetooth จะคืนค่า
02:00:00:00:00:00หรือค่าคงที่อื่น แทน MAC จริง เพื่อความเป็นส่วนตัว - Android 10 (API 29) ขึ้นไป: ต้องใช้ Permission
BLUETOOTH_PRIVILEGED(System App เท่านั้น) หรือใช้BluetoothAdapter.getAddress()ซึ่งอาจคืนค่า Anonymized Address - แอปทั่วไปไม่ควรพึ่งพา MAC Address เพื่อระบุตัวตนอุปกรณ์ ควรใช้
Settings.Secure.ANDROID_IDหรือ Advertising ID แทน