Giới thiệu
Ví dụ này minh họa cách kiểm tra xem Bluetooth của thiết bị có hỗ trợ LE 2M PHY (Bluetooth 5.0 Low Energy 2 Mbps PHY) hay không - cho phép truyền dữ liệu nhanh gấp đôi so với LE 1M.
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.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);
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
// Kiểm tra LE 2M PHY (yêu cầu API 26+ / Android 8.0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean supported = manager.getAdapter().isLe2MPhySupported();
textView.setText("Hỗ trợ LE 2M PHY: " + supported);
} else {
textView.setText("Yêu cầu Android 8.0+ (API 26)");
}
}
}
isLe2MPhySupported() (API 26+) kiểm tra hỗ trợ Bluetooth 5.0 LE 2M PHY - tốc độ 2 Mbps, khoảng cách ngắn hơn nhưng nhanh hơn LE 1M mặc định.
Bước 4: AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
Chạy ứng dụng
Chạy trên thiết bị Android 8.0+. Hiển thị true/false tùy phần cứng Bluetooth.
