添加权限:

<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. 1.Linux是什么?

    UNIX设计理念: 所有的程序或系统装置都是文件. 不管构建编辑器还是附属文件,所写的程序只有一个目的,就是有效地完成目标 操作系统:应用程序->系统调用->内核->硬件.其中系统调 ...

  2. [转]AS3 int uint Number

    转自:http://luhantu.iteye.com/blog/1910301 AS3 int uint Number 博客分类: AS3 flex number 类型  1) int 类可使用表示 ...

  3. C# 文件操作笔记

    C#中的文件操作 文件操作中的常见类: 静态类 File类:提供很多静态方法,用于移动.复制和删除文件. Directory类:用于移动.复制和删除目录. Path类:用于处理与路径相关的操作. 实例 ...

  4. 分布式缓存Memcached---开篇的话

    大数据.高并发这是最近一段时间内被IT行业提的最为火热的概念,看过<大数据时代>的同学应该不会陌生大数据的概念,尤其是对于互联网行业来说,大数据是每天都要接触的问题,简单通俗地说,每天得大 ...

  5. [转]ORACLE函数大全

    SQL中的单记录函数 1.ASCII返回与指定的字符对应的十进制数;SQL> select ascii('A') A,ascii('a') a,ascii('0') zero,ascii(' ' ...

  6. iOS XCode启用/关闭Clang Warnings

    前言:warnings是编码中很重要的一个环节,编译器给出合理的warning能帮助开发者找到自己代码的问题,防止很多bug产生.  默认用XCode创建一个工程,会自动开启一些重要的warnings ...

  7. AngularJS Best Practices: ng-include vs directive

    For building an HTML template with reusable widgets like header, sidebar, footer, etc. Basically the ...

  8. .NET中Redis安装部署及使用方法简介附->开源Redis操作辅助类

    Redis是一个用的比较广泛的Key/Value的内存数据库,新浪微博.Github.StackOverflow 等大型应用中都用其作为缓存,Redis的官网为http://redis.io/. Re ...

  9. FORTRAN 90标准函数(一) (转)

    符号约定: l  I代表整型;R代表实型;C代表复型;CH代表字符型;S代表字符串;L代表逻辑型;A代表数组;P代表指针;T代表派生类型;AT为任意类型. l  s:P表示s类型为P类型(任意kind ...

  10. 小Q系列之失恋

    这个题其实不难  仔细想想,, 注意题中要求的是一天是12个小时 #include<algorithm> #include<stdio.h> #include<math. ...