添加权限:

<uses-permission Android:name="android.permission.BLUETOOTH_ADMIN"/>

<uses-permission android:name="android.permission.BLUETOOTH"/>

  • 客户端

开启蓝牙:

/**

 * 打开蓝牙设备

 */

void openBT(){

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter!= null){

if (!mBluetoothAdapter.isEnabled()){

mBluetoothAdapter.enable();

Log.d("qfopenBT","打开蓝牙成功");

}

}

}

搜索蓝牙:

/**

 * 搜索蓝牙设备

 * @param view

 */

@OnClick(R.id.btSearch)

public void startSearch(View view){

if(mBluetoothAdapter!= null &&mBluetoothAdapter.isEnabled()){

if (!mBluetoothAdapter.isDiscovering()){

mBluetoothAdapter.startDiscovery();

}

}

}

开启搜索是异步操作,发现设备后会发送广播,所以要定义广播接收者

在接收到广播后,获取广播里的蓝牙数据

private class BTBroadCastRevextends BroadcastReceiver{

@Override

public void onReceive(Context context,Intent intent) {

String strAction = intent.getAction();

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

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

mArrDevice.add(device);

mAdapter.notifyDataSetChanged();

}

else if(strAction.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){

Log.d("qfonReceive","搜索完成");

}

}

}

//注册广播接收者

myReceive = newBTBroadCastRev();

IntentFilter ifFind = new IntentFilter(BluetoothDevice.ACTION_FOUND);

this.registerReceiver(myReceive,ifFind);

IntentFilter ifFinishFind = newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

this.registerReceiver(myReceive,ifFinishFind);

连接蓝牙,并开启发送数据线程:

/**

 * 点击item,连接对应的蓝牙设备

 */

protected void connectBT() {

mLvDevice.setOnItemClickListener(newAdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent,View view, int position, longid) {

MyClientTask task = newMyClientTask();

task.execute(mArrDevice.get(position));

}

});

}

class MyClientTask extends AsyncTask<BluetoothDevice,Void,Void>{

@Override

protected VoiddoInBackground(BluetoothDevice... devices) {

BluetoothDevice device = devices[0];

try {

//使用安全连接,服务端也要一样使用安全连接,UUID也要跟服务器的监听UUID一致

BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);

socket.connect();

Log.d("qfdoInBackground_client","连接成功,开始发送数据");

byte[] btMsg =new String("Hello").getBytes();

socket.getOutputStream().write(btMsg,0,btMsg.length);

} catch(Exception e) {

e.printStackTrace();

}

return null;

}

}

uuid可以通过uuidgen生成,生成结果类似以下结构:

5D3D5E52-338A-47B8-9F10-27ADF89E204E

  • 服务端

开启蓝牙,跟客户端一样

启动服务线程

new RevTask().execute();

class RevTask extendsAsyncTask<Void,Void,String>{

@Override

protected void onPostExecute(String s) {

super.onPostExecute(s);

tvMsg.setText(s);

}

@Override

protected StringdoInBackground(Void... params) {

try {

Log.d("qfdoInBackground","开始监听");

//要跟客户端uuid一致

BluetoothServerSocket sevSocket =mBluetoothAdapter.listenUsingRfcommWithServiceRecord("blue_service",MY_UUID_SECURE);

BluetoothSocket socket = sevSocket.accept();

if(socket != null){

Log.d("qfdoInBackground","连接成功");

InputStream stream = socket.getInputStream();

byte[] btRead =new byte[1024];

int iLength = stream.read(btRead);

Log.d("qfdoInBackground","读取数据成功"+iLength);

String strMsg =new String(btRead,"utf-8");

Log.d("qfdoInBackground",strMsg);

return strMsg;

}

else{

Log.d("qfdoInBackground","失败");

}

} catch (IOException e) {

e.printStackTrace();

Log.d("qfdoInBackground","异常");

}

return null;

}

}

上述代码没有实现配对,对应经典蓝牙通信,最好先进行配对再连接,已经配对的蓝牙设备可以直接通过adapter获取到

//得到所有已经配对的蓝牙适配器对象
Set<BluetoothDevice> devices = adapter.getBondedDevices();
            

没有配对的蓝牙设备,可以在扫描设备的广播通知中判断:

if

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

点击设备连接时,判断是否已经配对,如果已经配对,直接连接,如果没有配对,先配对:

  1. if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
  2. //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
  3. Method createBondMethod = BluetoothDevice.class
  4. .getMethod("createBond");
  5. Log.d("BlueToothTestActivity", "开始配对");
  6. returnValue = (Boolean) createBondMethod.invoke(btDev);
  7. }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
  8. connect(btDev);
  9. }

配对结果也会通过广播传递结果信息:

  1. // 注册Receiver来获取蓝牙设备相关的结果
  2. IntentFilter intent = new IntentFilter();
  3. intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
  4. intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  5. intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
  6. intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  7. registerReceiver(searchDevices, intent);
  1. if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
  2. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  3. switch (device.getBondState()) {
  4. case BluetoothDevice.BOND_BONDING:
  5. Log.d("BlueToothTestActivity", "正在配对......");
  6. break;
  7. case BluetoothDevice.BOND_BONDED:
  8. Log.d("BlueToothTestActivity", "完成配对");
  9. connect(device);//连接设备
  10. break;
  11. case BluetoothDevice.BOND_NONE:
  12. Log.d("BlueToothTestActivity", "取消配对");
  13. default:
  14. break;
  15. }

Android 蓝牙的更多相关文章

  1. android蓝牙打印机

    您还未登录!|登录|注册|帮助 首页 业界 移动 云计算 研发 论坛 博客 下载 更多 reality_jie的专栏 编程的过程是一种微妙的享受       目录视图 摘要视图 订阅 CSDN2013 ...

  2. Android蓝牙实例(和单片机蓝牙模块通信)

    最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码 ...

  3. Android 蓝牙4.0 BLE

    Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是蓝牙4.0的核心Profil ...

  4. android 蓝牙4.0 开发介绍

    最近一直在研究一个蓝牙功能 由于本人是菜鸟  学起来比较忙 一直搞了好久才弄懂 , 网上对蓝牙4.0也就是几个个dome 抄来抄去,全是英文注解 , 对英语不好的朋友来说 真是硬伤 , 一些没必要的描 ...

  5. 【转】android蓝牙开发---与蓝牙模块进行通信--不错

    原文网址:http://www.cnblogs.com/wenjiang/p/3200138.html 近半个月来一直在搞android蓝牙这方面,主要是项目需要与蓝牙模块进行通信.开头的进展很顺利, ...

  6. Android 蓝牙开发(整理大全)

    Android蓝牙开发 鉴于国内Android蓝牙开发的例子很少,以及蓝牙开发也比较少用到,所以找的资料不是很全. (一): 由于Android蓝牙的通信都需要用到UUID,如果由手机发起搜索,当搜索 ...

  7. android -- 蓝牙 bluetooth (四)OPP文件传输

    在前面android -- 蓝牙 bluetooth (一) 入门文章结尾中提到了会按四个方面来写这系列的文章,前面已写了蓝牙打开和蓝牙搜索,这次一起来看下蓝牙文件分享的流程,也就是蓝牙应用opp目录 ...

  8. android -- 蓝牙 bluetooth (三)搜索蓝牙

    接上篇打开蓝牙继续,来一起看下蓝牙搜索的流程,触发蓝牙搜索的条件形式上有两种,一是在蓝牙设置界面开启蓝牙会直接开始搜索,另一个是先打开蓝牙开关在进入蓝牙设置界面也会触发搜索,也可能还有其它触发方式,但 ...

  9. android -- 蓝牙 bluetooth (一) 入门

    前段时间在 网上看了一些关于android蓝牙的文章,发现大部分是基于老版本(4.1以前含4.1)的源码,虽然无碍了解蓝牙的基本原理和工作流程,但对着4.2.2的代码看起来总是有些遗憾.所以针对4.2 ...

  10. 深入了解Android蓝牙Bluetooth——《基础篇》

    什么是蓝牙?   也可以说是蓝牙技术.所谓蓝牙(Bluetooth)技术,实际上是一种短距离无线电技术,是由爱立信公司公司发明的.利用"蓝牙"技术,能够有效地简化掌上电脑.笔记本电 ...

随机推荐

  1. Qt之创建桌面和开始菜单快捷方式

    将安装好的酷狗拷贝到C:\data目录中 1.创建桌面快捷方式 QFile::link("C:/data/KuGou.exe", QStandardPaths::writableL ...

  2. WINDOWS下PhoneGap(Cordova)安装笔记

    1.首先下载Node.js  安装nodejs很简单直接点击安装文件下一步直至成功即可,安装notejs的同时npm也会同时安装 成功后打开notejs的命令行工具 输入“node -v”," ...

  3. 使用Python写Windows Service服务程序

    1.背景 如果你想用Python开发Windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用Python来做这个事情必须要借助第三方模块pywin32 ...

  4. springmvc 动态代理 JDK实现与模拟JDK纯手写实现。

    首先明白 动态代理和静态代理的区别: 静态代理:①持有被代理类的引用  ② 代理类一开始就被加载到内存中了(非常重要) 动态代理:JDK中的动态代理中的代理类是动态生成的.并且生成的动态代理类为$Pr ...

  5. RSA加密

    1.RSA的公钥和私钥到底哪个才是用来加密和哪个用来解密? 答:公钥加密私钥可解,私钥加密公钥可解. 2.RSA非对称加密特点? 答:算法强度复杂.加密解密速度比对称加密解密的速度慢.一个公钥,对外开 ...

  6. Win8电脑蓝屏并提示dpc_watchdog_violation

    用尽系统自带的工具均无法恢复,F8能进系统.后来使用如下方法解决了 这种错误情况的发生可能是由于 iastor.sys 驱动没有完全兼容 Windows 8系统所造成的. 微软正在研究一种可行方案,来 ...

  7. delphi中exit,abort,break,continue 的区别

    from:http://www.cnblogs.com/taofengli288/archive/2011/09/05/2167553.html delphi中表示跳出的有break,continue ...

  8. [原创] [YCM] YouCompleteMe安装完全指南

    因为实在实在受不鸟ctags了: 代码中有很多类具有相同名字的变量, 比如 "id". 当我想看下当前的这个 "id" 到底是哪个id的时候, 可怕的事情粗线了 ...

  9. mongodb群集

    项目目标:故障自动切换和自动修复成员节点,各个数据库之间数据完全一致.项目描述:副本集没有固定主节点,是整个集群选举得出的一个主节点,当其不工作时变    更其他节点.最小的副本集也应该具备一个pri ...

  10. NOI 05:最高的分数描述

    描述 孙老师讲授的<计算概论>这门课期中考试刚刚结束,他想知道考试中取得的最高分数.因为人数比较多,他觉得这件事情交给计算机来做比较方便.你能帮孙老师解决这个问题吗? 输入输入两行,第一行 ...