添加权限:

<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. PHP底层工作原理

    最近搭建服务器,突然感觉lamp之间到底是怎么工作的,或者是怎么联系起来?平时只是写程序,重来没有思考过他们之间的工作原理: PHP底层工作原理 图1 php结构 从图上可以看出,php从下到上是一个 ...

  2. 早上遇到err_content_decoding_fail错误

    网站在手机端出现一个error: err_content_decoding_fail. 查了一下,应该是文件编码出问题了. 但这两天都很小代码级别的改动,编码的问题一般都是会在覆盖文件的时候才出现. ...

  3. C#基础知识记录一

    C#基础知识记录一 static void Main(string[] args) { #region 合并运算符的使用(合并运算符??) 更多运算符请参考:https://msdn.microsof ...

  4. val()失效

    在表单设置了disabled或者readonlye,那么val()方会失效,可以采用$().attr('value','')

  5. :active 为什么在ios上失效

    :active是针对鼠标,而手机上是没有鼠标,而是touchstart,所以早成了ios上不兼容 解决方法是: window.onload = function(){ document.body.ad ...

  6. 【转载】APP留存率多少才合格——全面解析留存率

    做产品经理的一般都会关注以下 提高用户留存率 提高用户粘性和活跃度     这些天,有几位朋友都找我聊产品的留存率,有做手游的,做工具的,做社交APP的,于是把以前写过的留存率文章翻出来.   次日留 ...

  7. 使用JCIFS获取远程共享文件

    package com.jadyer.util;  import java.io.File; import java.io.FileOutputStream; import java.io.IOExc ...

  8. Java提高篇——JVM加载class文件的原理机制

    在面试java工程师的时候,这道题经常被问到,故需特别注意. 1.JVM 简介 JVM 是我们Javaer 的最基本功底了,刚开始学Java 的时候,一般都是从“Hello World ”开始的,然后 ...

  9. Windows Server 2008 R2组策略创建用户桌面快捷方式

    问题: 如何让所有域用户桌面有一个公司共享的快捷方式,让所有域用户直接双击就能打开公司共享. 解决办法: 1.创建一个zhuyu组织单元 ----- 在zhuyu组织单元创建一个域用户user1. 2 ...

  10. PostgreSQL Replication之第一章 理解复制概念(1)

    PostgreSQL Replication系列翻译自PostgreSQL Replication一书 在本章中,将会介绍不同的复制概念,您会了解哪些类型的复制对哪一种实用场景是最合适的. 在本章的最 ...