Android蓝牙开发——搜索设备

1、获取本地蓝牙适配器

      BluetoothAdapter
mAdapter= BluetoothAdapter.getDefaultAdapter();

  

2、打开蓝牙

      if(!mAdapter.isEnabled()){

//弹出对话框提示用户是后打开

Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler, REQUEST_ENABLE);

      //不做提示,强行打开

      // mAdapter.enable();

}

 

  3、搜索设备

1)刚才说过了mAdapter.startDiscovery()

是第一步,可以你会发现没有返回的蓝牙设备,怎么知道查找到了呢?向下看,不要急

 2)定义BroadcastReceiver,关于BroadcastReceiver不多讲了,不是今天的讨论内容,代码如下


BroadcastReceiver mReceiver = new BroadcastReceiver() {

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

                   //找到设备

if (BluetoothDevice.ACTION_FOUND.equals(action)) {

BluetoothDevice device = intent

.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

Log.v(TAG, "find device:" + device.getName()

+ device.getAddress());

}

}

         //搜索完成

        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED

.equals(action)) {

setTitle("搜索完成");

if (mNewDevicesAdapter.getCount() == 0) {

Log.v(TAG,"find over");

}

}

//执行更新列表的代码

}

};

  这样,没当查找到新设备或是搜索完成,相应的操作都在上段代码的两个if里执行了,不过前提是你要先注册

BroadcastReceiver,具体代码如下

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver, filter);

filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

registerReceiver(mReceiver, filter);

(这段代码,一般写在onCreate()里..)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值