Android 蓝牙自动连接实现

本文介绍了在Android中实现蓝牙设备自动连接的步骤,包括注册蓝牙广播、搜索设备、配对和建立连接。关键在于调用autoConnect()方法,通过BluetoothDevice ACTION_FOUND广播获取设备地址。
摘要由CSDN通过智能技术生成

Android连接蓝牙设备一般有这几个步奏

1、注册蓝牙相关的广播

        IntentFilter intent = new IntentFilter(); 
        intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果 
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); 
        intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); 
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); 
        registerReceiver(searchDevices, intent); 

2、搜索蓝牙设备

     BluetoothAdapter.getDefaultAdapter().startDiscovery();

3、配对

btDev.createBond();

4、建立连接

    private void connect(BluetoothDevice btDev) { 
        UUID uuid = UUID.fromString(SPP_UUID); 
        try { 
           // btSocket = btDev.createRfcommSocketToServiceRecord(uuid); 
            btSocket =(BluetoothSocket) btDev.getClass().getMethod("createRfcommSocket", new Class[] {
  int.class}).invoke(btDev,1);

            Log.d("BlueToothTestActivity", "开始连接..."); 
            btSocket.connect(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block
             Log.e("BlueToothTestActivity", "开始连接......链接失败"); 
            e.printStackTrace(); 
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }

此处不抛出异常即可连接成功

完整代码:

package com.example.bluetoothtest;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值