Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีปิด Bluetooth ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีปิด Bluetooth ผ่านโปรแกรม โดยใช้ BluetoothManager และ BluetoothAdapter.disable() หมายเหตุ: ตั้งแต่ Android 10 (API 29) ไม่สามารถปิด/เปิด Bluetooth โดยตรงผ่านโปรแกรมได้แล้ว ต้องนำทางผู้ใช้ไปที่ Settings

ขั้นตอนการสร้างโปรเจกต์

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (res/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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp"
        android:gravity="center"
        android:text="กดเพื่อปิด Bluetooth"
        android:clickable="true"
        android:focusable="true" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (src/MainActivity.java)

package com.example.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    BluetoothAdapter bluetoothAdapter;

    @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);
        
        // ใช้ BluetoothManager (API 18+) หรือ BluetoothAdapter.getDefaultAdapter()
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disableBluetooth();
            }
        });
    }

    private void disableBluetooth() {
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "อุปกรณ์ไม่รองรับ Bluetooth", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "Bluetooth ปิดอยู่แล้ว", Toast.LENGTH_SHORT).show();
            return;
        }

        // ตรวจสอบ API Level
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ ไม่อนุญาตให้ปิด Bluetooth โดยตรง
            // ต้องเปิด Settings ให้ผู้ใช้ปิดเอง
            Intent intent = new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
            startActivity(intent);
            Toast.makeText(this, "กรุณาปิด Bluetooth ในการตั้งค่า", Toast.LENGTH_LONG).show();
        } else {
            // Android 9 และก่อนหน้า - ปิดได้โดยตรง (ต้องการ Permission BLUETOOTH_ADMIN)
            boolean success = bluetoothAdapter.disable();
            if (success) {
                Toast.makeText(this, "กำลังปิด Bluetooth...", Toast.LENGTH_SHORT).show();
                textView.setText("Bluetooth: ปิด");
            } else {
                Toast.makeText(this, "ปิด Bluetooth ไม่สำเร็จ", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml - Permissions

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <!-- สำหรับ Android 9 และก่อนหน้า -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <!-- สำหรับ Android 12+ (API 31+) -->
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

    <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>

สรุปการเปลี่ยนแปลงตาม API Level

API LevelAndroid Versionสามารถปิด/เปิด Bluetooth โดยโปรแกรมได้?วิธีที่แนะนำ
< 29Android 9 และก่อนได้ (ต้อง BLUETOOTH_ADMIN)bluetoothAdapter.disable()
29 (Q)Android 10ไม่ได้ (Restricted)Intent → Settings
>= 31 (S)Android 12+ไม่ได้Intent → Settings + BLUETOOTH_CONNECT permission

โค้ดรองรับทุก Version (Best Practice)

public void toggleBluetooth(boolean enable) {
    if (bluetoothAdapter == null) return;
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        // Android 10+ : นำทางไป Settings
        Intent intent = new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
        startActivity(intent);
    } else {
        // Android 9 และก่อน : ควบคุมโดยตรง
        if (enable) {
            bluetoothAdapter.enable();
        } else {
            bluetoothAdapter.disable();
        }
    }
}

ข้อควรระวัง

  • Android 10+: Google จำกัดการควบคุม Radio (Bluetooth, WiFi) โดยตรง เพื่อความปลอดภัยและความเป็นส่วนตัว
  • ต้องขอ Permission BLUETOOTH_CONNECT (API 31+) สำหรับการเชื่อมต่อ/จัดการอุปกรณ์ Bluetooth
  • แอป System/Pre-installed เท่านั้นที่อาจได้ Exception
  • ใช้ ACTION_BLUETOOTH_SETTINGS หรือ ACTION_WIRELESS_SETTINGS เพื่อนำทางผู้ใช้