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

Cách bật Bluetooth trên Android

Giới thiệu

Ví dụ này minh họa cách bật Bluetooth theo chương trình bằng BluetoothManager.getAdapter().enable().

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 để bậ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().enable();
                }
            }
        });
    }
}

Bước 4: AndroidManifest.xml

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Lưu ý quan trọng: Tương tự tắt Bluetooth, từ Android 10 (API 29) ứng dụng bình thường không được phép bật Bluetooth trực tiếp. Cần dùng Intent BluetoothAdapter.ACTION_REQUEST_ENABLE để yêu cầu người dùng xác nhận.

Chạy ứng dụng

Chạy trên thiết bị Android < 10. Nhấn TextView để bật Bluetooth.

Cách bật Bluetooth trên Android