ble

 avatar
unknown
plain_text
10 months ago
6.7 kB
6
Indexable

package com.example.bluetooth;
 
import static android.content.ContentValues.TAG;
 
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
 
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
 
import java.util.ArrayList;
 
 
public class MainActivity extends AppCompatActivity {
    public final int REQUEST_ENABLE_BT = 1;
    BluetoothAdapter bluetoothAdapter;
    BluetoothManager bluetoothManager;
    BluetoothLeScanner bluetoothLeScanner;
    boolean scanning;
    Handler handler = new Handler();
    ArrayList<BluetoothDevice> bluetoothDevices = new ArrayList<>();
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        bluetoothManager = getSystemService(BluetoothManager.class);
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter == null) {
            // Device doesn't support Bluetooth
            System.out.println("Thiet bi khong ho tro bluetooth!");
        }
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
 
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        scanLeDevice();
    }
 
    private void scanLeDevice() {
        if (!scanning) {
            // Stops scanning after a predefined scan period.
            Log.d(TAG, "Starting BLE scan");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "Stopping BLE scan");
                    scanning = false;
                    if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    bluetoothLeScanner.stopScan(leScanCallback);
                }
            }, SCAN_PERIOD);
 
            scanning = true;
            bluetoothLeScanner.startScan(leScanCallback);
        } else {
            Log.d(TAG, "Stopping BLE scan");
            scanning = false;
            bluetoothLeScanner.stopScan(leScanCallback);
            logDevices();
        }
    }
 
    private ScanCallback leScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (!bluetoothDevices.contains(device)) {
                bluetoothDevices.add(device);
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                Log.d(TAG, "Thiết bị mới: " + device.getName() + " - " + device.getAddress());
            }
        }
    };
 
    private void logDevices() {
        Log.d(TAG, "Danh sách các thiết bị tìm thấy:");
        for (BluetoothDevice device : bluetoothDevices) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            String deviceName = device.getName() != null ? device.getName() : "Unknown Device";
            String deviceAddress = device.getAddress();
            Log.d(TAG, "Thiết bị: " + deviceName + " - Địa chỉ: " + deviceAddress);
        }
    }
}
Editor is loading...
Leave a Comment