Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách tắt Bluetooth trên Android

Giới thiệu

Ví dụ này minh họa cách tắt Bluetooth theo chương trình trên Android bằng BluetoothManager.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Thiết kế giao diện (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:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.myapplication;

import android.bluetooth.BluetoothManager;
import android.content.Context;
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;

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);
        textView.setText("Nhấn để tắt Bluetooth");

        final BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (manager.getAdapter() != null) {
                    manager.getAdapter().disable();
                }
            }
        });
    }
}

Lưu ý quan trọng: Từ Android 10 (API 29), ứng dụng không được phép bật/tắt Bluetooth trực tiếp. Cần dùng BluetoothAdapter.enable()/disable() chỉ dành cho ứng dụng hệ thống hoặc dùng Intent BluetoothAdapter.ACTION_REQUEST_ENABLE/DISABLE để nhờ người dùng xác nhận.

Bước 4: Cấp quyền trong AndroidManifest.xml

<?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" />
    <application ...>
        <activity android:name=".MainActivity">...</activity>
    </application>
</manifest>

Chạy ứng dụng

Chạy trên thiết bị thật (API < 29). Nhấn vào TextView để tắt Bluetooth.

Cách tắt Bluetooth trên Android