低功耗蓝牙

低功耗蓝牙获取当前设备取到的特征值

xml代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".NewMainActivity">

    <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="19dp"
    android:text="搜索蓝牙" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button"
        android:layout_marginBottom="14dp"
        android:layout_marginLeft="45dp"
        android:layout_marginStart="45dp"
        android:layout_toEndOf="@+id/button"
        android:layout_toRightOf="@+id/button"
        android:text="初始状态" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/button"
        android:layout_marginLeft="12dp"
        android:layout_marginStart="12dp"
        android:text="蓝牙设备如下:" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_below="@+id/textView"
        tools:ignore="NestedScrolling" />


</RelativeLayout>

java代码

package com.automator.bluetooth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.List;

public class NewMainActivity extends AppCompatActivity{
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothManager bluetoothManager;

    private TextView text1,text2,text3,text4;
    private Button button;
    private static final String TAG = "MainActivity";
    private BluetoothDevice device;

    ListView listView;

    List<String> list = new ArrayList<>();
    List<String> addList = new ArrayList<>();
    String address = "";

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text1 = findViewById(R.id.textView);
        text2 = findViewById(R.id.textView2);
        button = findViewById(R.id.button);

        listView = findViewById(R.id.listView);


        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();


        if (bluetoothAdapter == null){
            Toast.makeText(this,"设备不支持蓝牙", Toast.LENGTH_SHORT).show();
        }
        if (!bluetoothAdapter.isEnabled()){
            bluetoothAdapter.enable();
        }

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter);
        IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver,filter1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
                text2.setText("正在搜索...");

                list.clear();
            }
        });

    }

    /**
     * 动态处理权限
     */
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        1);
                Log.d(TAG, "没有权限,请求权限");
                return;
            } else {
                /**
                 * 如果已经同意了该权限则开始搜索设备
                 */
                bluetoothAdapter.startDiscovery();

            }
            Log.d(TAG, "已有定位权限");
        }
    }


    /**
     * 申请权限回调方法 处理用户是否授权
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    /**
                     * 用户同意授权开始搜索设备
                     */
                    bluetoothAdapter.startDiscovery();

                } else {
                    //用户拒绝授权 则给用户提示没有权限功能无法使用,
                    Log.d(TAG, "没有定位权限,请先开启!");
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }


    /**
     * 创建广播接收器
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.R)
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {


            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)){
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
                bluetoothAdapter = bluetoothManager.getAdapter();

                list.add("\n" + device.getName() + "==>" + device.getAddress() + "\n");
                addList.add(device.getAddress());

                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewMainActivity.this, android.R.layout.simple_list_item_1, list);
                listView.setAdapter(arrayAdapter);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        BluetoothDevice bluetoothDevice ;

                        bluetoothDevice = bluetoothAdapter.getRemoteDevice(addList.get(position));
                        bluetoothDevice.connectGatt(NewMainActivity.this, false, gattCallback);
                        address = addList.get(position);
                        Log.d("点击蓝牙", listView.getItemAtPosition(position) + "");

                    }
                });


                Log.d("搜索蓝牙设备如下", device.getName() + "==>" + device.getAddress());

            }else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                text2.setText("搜索完成");
            }
        }

    };


    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 成功连接,可以进一步读取设备的特定服务和特性
                gatt.discoverServices();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 通过蓝牙Gatt服务和特性获取更多设备信息
                List<BluetoothGattService> services = gatt.getServices();
                // 遍历服务并查找包含设备信息的特性,比如Manufacturer Data或User Defined Service
                for (BluetoothGattService service : services) {
                    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                    for (BluetoothGattCharacteristic characteristic : characteristics) {

                        gatt.readCharacteristic(characteristic);
                    }
                }
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                byte[] data = characteristic.getValue();
                // 解析特性数据以获取更多信息,例如iPhone设备的特定标识或状态信息
                Log.d(TAG,"搜索蓝牙设备如下 onCharacteristicRead + " + address + " " + new String(data) + " " );

            }
        }
    };

}

添加权限

 <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
 <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
  <uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS"
        tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!--6.0之后需要定位权限-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值