添加权限:

<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. Linux 升级修改libc gcc 文件名称,导致执行命令失效问题解决

    升级linux文件时,若不小心把文件名给重命名了,结果导致执行所有命令都不识别. 比如我们不小心执行了 mv /lib64/libc.so.6 /lib64/libc.so.6.bak 结果导致所有系 ...

  2. Inventory Costing in AX 2009

    I wanted to explore some scenarios that illustrate a few important concepts related to inventory cos ...

  3. WP8.1 模仿手机通讯记录的选择框

    2016年11月6日 更新: 其实 这个有一个非常简单的方法.非常简单... ListView SelectionMode="Multiple" 这个一XAML  代码就可以解决了 ...

  4. mysql主键uuid、uuid_short和int自增对比

    数据库主键性能对比: 名称 存储长度 生成方式 1. uuid 32+4 uuid()函数 2. uuid20 20 UUID_SHORT()函数 3. bigint自增 20 auto_increm ...

  5. [CC]区域生长算法——点云分割

    基于CC写的插件,利用PCL中算法实现: void qLxPluginPCL::doRegionGrowing() { assert(m_app); if (!m_app) return; const ...

  6. svn 架设

    1.yum install subversion  openssl-devel -y 2. cd /data/svn 3. svnadmin create remote 4. 编辑conf 下 aut ...

  7. H5点击事件兼容各种APP浏览器

    https://github.com/Clouda-team/touchjs/blob/master/touch.min.js <script src="js/jquery.min.j ...

  8. Java中对象创建过程

    本文介绍的对象创建过程仅限于普通Java对象,不包括数组和Class对象. 1.类加载检查 虚拟机遇到一条new指令时,首先去检查该指令的参数能否在常量池中定位到一个类的符号引用,并且检查这个符号引用 ...

  9. Windows Phone 十八、加速计

    加速度传感器 手机的加速度传感器工作时是通过 x.y.z 三个轴的偏移来计算的 在代码基本的 API 主要集中在 Accelerometer 类型中 主要是使用该类型的对象捕获 ReadingChan ...

  10. pod install 无限卡顿

    pod install  被墙了,请大家换成pod install --verbose --no-repo-update