android 蓝牙app代码

本文详细介绍了一款基于蓝牙4.0的应用开发过程,包括如何使用Android系统进行蓝牙设备的扫描、连接及数据交互等核心步骤。文章通过具体实例演示了如何实现蓝牙设备的查找、服务与特征值的读取等功能。

为了自己忘记,也为了他人的方便,全码在此!!!

private BluetoothGatt bluetoothGatt;
private BluetoothGattService gattService;
private BluetoothGattCharacteristic gattCharacteristic;
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private List<BluetoothDevice> devices = new ArrayList<>();

private  UUID serviceUUID;    //不同设备  不同uuid
private  UUID characteristicUUID;      //不同设备  不同uuid
private final UUID service4UUID= UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");   
private final UUID charAUUID = UUID.fromString("0000fffa-0000-1000-8000-00805f9b34fb");

private LightReceiver lightReceiver;
private ScanReceiver scanReceiver;
private ListView listView;
private TextView tvrefresh;
private String lightAction;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.i("tag", "MainActivity   onCreate()");
    //
    listView = (ListView) findViewById(R.id.lv_bluetooth);
    tvrefresh = (TextView) findViewById(R.id.tv_refresh_bluetooth);
    tvrefresh.setOnClickListener(this);
    openBluetooth();
    registeLigthReceiver();
    registeScanReceiver();

}

@Override
protected void onStart() {
    super.onStart();
    Log.i("tag", "MainActivity   onStart()");
    bluetoothScan();
}

//返回
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    Log.i("tag", "MainActivity    onKeyUp()");
    this.finish();
    return super.onKeyUp(keyCode, event);
}

//重新扫描蓝牙
@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.tv_refresh_bluetooth:
            //蓝牙扫描
            bluetoothScan();
            break;
        default:
            break;
    }
}

//打开本地蓝牙
private void openBluetooth() {
    Log.i("tag", "openLocalBluetooth()");
    //检查手机是否支持蓝牙4.0
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "手机不支持蓝牙4.0", Toast.LENGTH_SHORT).show();
        finish();
    }
    //调用系统服务的方式,请求开启蓝牙
    bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();
    //开启蓝牙
    if (!bluetoothAdapter.isEnabled()) {
        bluetoothAdapter.enable();
    }
}

//开始蓝牙扫描   扫描到一个添加一个
private void bluetoothScan() {
    Log.i("tag", "bluetoothScan()");
    if (bluetoothAdapter == null) {
        openBluetooth();
    }
    if (!bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.startDiscovery();    //回调
    } else {
        Toast.makeText(this, "扫描中..", Toast.LENGTH_SHORT).show();
    }
}

//更新蓝牙列表中的数据
private void updateUi() {
    Log.i("tag", "updateUi()");
    if (devices != null && devices.size() > 0) {
        BlueAdapter adapter = new BlueAdapter(this, devices);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    } else {
        Toast.makeText(this, "附近没有蓝牙", Toast.LENGTH_SHORT).show();
    }
}

//取得gatt 对应的service
private BluetoothGattService getGattService(BluetoothGatt gatt, UUID serviceUUID) {
    List<BluetoothGattService> gattServices = gatt.getServices();
    for (BluetoothGattService gattService : gattServices) {
        if (gattService.getUuid().equals(serviceUUID)) {
            return gattService;
        }
    }
    return null;
}

//取得service对应的characteristic
private BluetoothGattCharacteristic getGattCharacteristic(BluetoothGattService gattService, UUID characteristicUUID) {
    List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
    for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
        if (gattCharacteristic.getUuid().equals(characteristicUUID)) {
            return gattCharacteristic;
        }
    }
    return null;
}

//注册蓝牙扫描监听
private void registeScanReceiver() {
    Log.i("tag", "registeScanReceiver()");
    scanReceiver = new ScanReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(scanReceiver, filter);
}

//定义蓝牙扫描监听类 添加device , 更新界面
class ScanReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("tag", " BluetoothReceiver / ScanReceiver onReceive()   action=" + intent.getAction());
        String scanAction = intent.getAction();
        if (scanAction.equals(BluetoothDevice.ACTION_FOUND)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (!devices.contains(device)) {
                devices.add(device);
                if (CacheUtils.getBlueDeviceString(MainActivity1.this, device.getAddress()).equals("")) {
                    CacheUtils.putBlueDeviceString(MainActivity1.this, device.getAddress(), device.getName());
                }
                updateUi();
            }
        } else if (scanAction.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
            if (devices == null || devices.size() == 0) {
                Toast.makeText(MainActivity1.this, "附近没有发现蓝牙设备", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

//注册灯光监听
private void registeLigthReceiver() {
    Log.i("tag", "registeReceiver()");
    lightReceiver = new LightReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction("openLight");
    filter.addAction("closeLight");
    registerReceiver(lightReceiver, filter);
}

//定义灯控监听类
class LightReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i("tag", " BluetoothReceiver    /LightReceiver onReceive()   action=" + intent.getAction());
        //
        String address = intent.getStringExtra("bluetoothAddress");   //从adapter取得的数据
        lightAction = intent.getAction();
        // if()     不同设备   不同serviceUUID,不同的characteristicUUID  自己确定
        serviceUUID=service4UUID;
        characteristicUUID=charAUUID;

        if (bluetoothAdapter == null) {
            openBluetooth();
        }
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);   
        MyBluetoothGattCallback gattCallback = new MyBluetoothGattCallback();
        bluetoothGatt = device.connectGatt(MainActivity1.this, false, gattCallback);   //回调

    }
}

//蓝牙连接/通信回调
class MyBluetoothGattCallback extends android.bluetooth.BluetoothGattCallback {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);
        Log.i("tag", "MyBluetoothGattCallback    onConnectionStateChange()    newState=" + newState);
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            gatt.discoverServices();              //连接成功,开始搜索服务,一定要调用此方法,否则获取不到服务
            Log.i("tag", "MyBluetoothGattCallback   STATE_CONNECTED    ");
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            Log.i("tag", "MyBluetoothGattCallback    STATE_DISCONNECTED");
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        Log.i("tag", "MyBluetoothGattCallback    onServicesDiscovered()  status=" + status);

        if (lightAction.equals("openLight") || lightAction.equals("closeLight")) {    //避免  不停更新
            if (gattService == null || gattCharacteristic == null || !serviceUUID.equals(service4UUID) || !characteristicUUID.equals(charAUUID)) {
                gattService = getGattService(gatt, serviceUUID);
                if (gattService != null) {
                    gattCharacteristic = getGattCharacteristic(gattService, characteristicUUID);
                    if (gattCharacteristic != null) {
                        gatt.setCharacteristicNotification(gattCharacteristic, true);
                        gatt.connect();
                    }
                }
            }
            if (lightAction.equals("openLight")) {
                gattCharacteristic.setValue("openLight");  //这里自己设置 蓝牙模组需要的数据
                gatt.writeCharacteristic(gattCharacteristic);
            } else if (lightAction.equals("closeLight")) {
                gattCharacteristic.setValue("closeLight");  //这里自己设置 蓝牙模组需要的数据
                gatt.writeCharacteristic(gattCharacteristic);
            }
            lightAction = "";
            gatt.readRemoteRssi();
        }
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.i("tag", "onDestroy()");
    if (bluetoothAdapter != null) {
        bluetoothAdapter.disable();
        bluetoothAdapter = null;
    }
    if (bluetoothGatt != null) {
        bluetoothGatt.disconnect();
        bluetoothGatt.close();
        bluetoothGatt = null;
    }

    if (lightReceiver != null) {
        unregisterReceiver(lightReceiver);
        lightReceiver = null;
    }
    if (scanReceiver != null) {
        unregisterReceiver(scanReceiver);
        scanReceiver = null;
    }
}

Android蓝牙应用程序的代码包括以下几个方面: 1. 搜索和配对蓝牙设备:可以使用BluetoothAdapter类和BluetoothDevice类来搜索和配对设备,可以通过调用startDiscovery()方法开始搜索设备,使用createBond()方法进行配对。 2. 连接蓝牙设备:使用BluetoothSocket类创建一个蓝牙套接字来与远程设备进行通信,可以使用connect()方法连接到远程设备。 3. 传输数据:使用BluetoothSocket类的getOutputStream()和getInputStream()方法获取输出和输入流进行数据传输。 4. 监听蓝牙连接状态:使用BroadcastReceiver监听蓝牙连接状态变化,如ACTION_ACL_CONNECTED、ACTION_ACL_DISCONNECTED等。 以下是一个简单的Android蓝牙应用程序示例代码: ``` public class BluetoothActivity extends AppCompatActivity { private BluetoothAdapter bluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bluetooth); // 获取蓝牙适配器 bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } // 搜索设备 public void searchDevice() { if (bluetoothAdapter.isDiscovering()) { bluetoothAdapter.cancelDiscovery(); } bluetoothAdapter.startDiscovery(); } // 配对设备 public void pairDevice(BluetoothDevice device) { try { Method method = device.getClass().getMethod("createBond", (Class[]) null); method.invoke(device, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } } // 连接设备 public void connectDevice(BluetoothDevice device) { BluetoothSocket socket = null; try { socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); socket.connect(); OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); // 进行数据传输 } catch (IOException e) { e.printStackTrace(); } } // 监听连接状态 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { // 设备已连接 } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { // 设备已断开连接 } } }; @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(receiver, filter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); } } ```
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值