Android蓝牙通信

Android为蓝牙设备之间的通信封装好了一些调用接口,使得实现Android的蓝牙通信功能并不困难。可通过UUID使两个设备直接建立连接。

具体步骤:

1.  获取BluetoothAdapter实例,注册一个BroadcastReceiver监听蓝牙扫描过程中的状态变化

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action))
            {
                // Get the BluetoothDevice object from the Intent
            	// 通过EXTRA_DEVICE附加域来得到一个BluetoothDevice设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // If it's already paired, skip it, because it's been listed already
                // 如果这个设备是不曾配对过的,添加到list列表
                if (device.getBondState() != BluetoothDevice.BOND_BONDED)
                {
                	list.add(new ChatMessage(device.getName() + "\n" + device.getAddress(), false));
                	clientAdapter.notifyDataSetChanged();
            		mListView.setSelection(list.size() - 1);
                }
            // When discovery is finished, change the Activity title
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
                setProgressBarIndeterminateVisibility(false);
                if (mListView.getCount() == 0)
                {
                	list.add(new ChatMessage("没有发现蓝牙设备", false));
                	clientAdapter.notifyDataSetChanged();
            		mListView.setSelection(list.size() - 1);
                }
            }
        }
    };

2.  打开蓝牙(enable),并设置蓝牙的可见性(可以被其它设备扫描到,客户端是主动发请求的,可不设置,服务端必须设置可见)。

               if (mBluetoothAdapter != null) {
			if (!mBluetoothAdapter.isEnabled()) {
				// 发送打开蓝牙的意图,系统会弹出一个提示对话框
        		Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        		startActivityForResult(enableIntent, RESULT_FIRST_USER);

        		// 设置蓝牙的可见性,最大值3600秒,默认120秒,0表示永远可见(作为客户端,可见性可以不设置,服务端必须要设置)
        		Intent displayIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        		displayIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        		startActivity(displayIntent);

        		// 直接打开蓝牙
        		mBluetoothAdapter.enable();
			}
		}

3.  扫描,startDiscovery()方法是一个很耗性能的操作,在扫描之前可以先使用getBondedDevices()获取已经配对过的设备(可直接连接),避免不必要的消耗。

      private void scanDevice() {
		// TODO Auto-generated method stub
    	if (mBluetoothAdapter.isDiscovering()) {
			mBluetoothAdapter.cancelDiscovery();
		} else {

			// 每次扫描前都先判断一下是否存在已经配对过的设备
		    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
		    if (pairedDevices.size() > 0) {
		        for (BluetoothDevice device : pairedDevices) {
		            list.add(new ChatMessage(device.getName() + "\n" + device.getAddress(), true));
		        }
		    } else {
		        	list.add(new ChatMessage("No devices have been paired", true));
		        	clientAdapter.notifyDataSetChanged();
		    		mListView.setSelection(list.size() - 1);
		     }
	             /* 开始搜索 */
	             mBluetoothAdapter.startDiscovery();
		}
	}

4.  通过Mac地址发送连接请求,在这之前必须使用cancelDiscovery()方法停止扫描。

                mBluetoothAdapter.cancelDiscovery();

		// 通过Mac地址去尝试连接一个设备
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothMsg.BlueToothAddress);

5.  通过UUID使两个设备之间建立连接。

客户端:主动发请求

     BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

     // 通过socket连接服务器,这是一个阻塞过程,直到连接建立或者连接失效
     socket.connect();

服务端:接受一个请求

     BluetoothServerSocket mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
						UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));		

     /* 接受客户端的连接请求 */
     // 这是一个阻塞过程,直到建立一个连接或者连接失效
     // 通过BluetoothServerSocket得到一个BluetoothSocket对象,管理这个连接
     BluetoothSocket socket = mServerSocket.accept();

6.  通过InputStream/outputStream读写数据流,已达到通信目的。

     OutputStream os = socket.getOutputStream();
     os.write(msg.getBytes());
     InputStream is = null;
     try {
         is = socket.getInputStream();
     } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }

7.  关闭所有线程以及socket,并关闭蓝牙设备(disable)。

                        if (mClientThread != null) {
    				mClientThread.interrupt();
    				mClientThread = null;
				}
    			if (mReadThread != null) {
					mReadThread.interrupt();
					mReadThread = null;
				}
    			try {
					if (socket != null) {
						socket.close();
						socket = null;
					}
				} catch (IOException e) {
					// TODO: handle exception
				}
                if (mBluetoothAdapter != null) {
			mBluetoothAdapter.cancelDiscovery();
			// 关闭蓝牙
			mBluetoothAdapter.disable();
		}
		unregisterReceiver(mReceiver);

主要步骤就是这些,为了能够更好的理解,我将服务器端和客户端的代码分开来写了两个程序,下载地址:http://download.csdn.net/detail/visionliao/8417235

时间: 2024-08-26 03:33:40

Android蓝牙通信的相关文章

android 蓝牙通信编程

转自:http://blog.csdn.net/yudajun/article/details/8362916 公司项目涉及蓝牙通信,所以就简单的学了学,下面是自己参考了一些资料后的总结,希望对大家有帮助. 以下是开发中的几个关键步骤: 1,首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket,获取输入输出流 4,读取和写入数据 5,断开连接关闭蓝牙 下面是一个demo 效果图: SearchDeviceActivity.java [java] view plaincopy package 

Android蓝牙通信详解

蓝牙通信的大概步骤如下: 1,首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket,获取输入输出流 4,读取和写入数据 5,断开连接关闭蓝牙 还要发送配对码发送进行判断! 下面是所有的源代码:不会很难:认真看: SearchDeviceActivity.java [java] view plaincopy package com.hello.project; import java.util.ArrayList; import java.util.Iterator; import java.

Android蓝牙通信总结

这篇文章要达到的目标: 1.介绍在Android系统上实现蓝牙通信的过程中涉及到的概念. 2.在android系统上实现蓝牙通信的步骤. 3.在代码实现上的考虑. 4.例子代码实现(手持设备和蓝牙串口设备通信). 1.介绍在Android系统上实现蓝牙通信的过程中使用到的类 BluetoothAdapter Represents the local Bluetooth adapter (Bluetooth radio). The BluetoothAdapter is the entry-poi

Android 蓝牙通信

Android 蓝牙传文件比较常见,但是官方也给出了基于蓝牙通讯做了个聊天室的sample,BluetoothChat.有兴趣的可以下载看下,很有意思.通讯那块用了特殊的BluetoothSocket.思路跟一般socket通讯一样.必须有服务端和客户端.sample有三个类:BluetoothChat,BluetoothChatService,DeviceListActivity. BluetoothChat是主界面,可以看到聊天的内容,BluetoothChatService是功能类,实现了

(转)android 蓝牙通信编程

转自:http://blog.csdn.net/pwei007/article/details/6015907 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输. 本文档描述了怎样利用android平台提供的蓝牙API去实现蓝牙设备之间的通信,蓝牙设备之间的通信主要包括了四个步骤:设置蓝牙设备.寻找局域网内可能或者匹配的设备.连接设备和设备之间的数据传输.以下是建立蓝牙连接的所需要的一些基本类: BluetoothAdapter类:代表了一个本地的蓝牙适配器.他是所有蓝牙交互

android 蓝牙 通信 bluetooth

此例子基于 android demo Android的蓝牙开发,虽然不多用,但有时还是会用到,  Android对于蓝牙开发从2.0版本的sdk才开始支持,而且模拟器不支持,测试需要两部手机: 由于公司用到了蓝牙,所以学习了一下,也和大家分享一下! 总体来说和网络 socket 很相似,监听,连接,成功后,发送数据:   我将蓝牙分成了客户端和服务端,下载地址:   http://download.csdn.net/detail/q610098308/8681065   第一步: 先要在Andr

Android 蓝牙 通信

Android中蓝牙模块的使用 1. 使用蓝牙的响应权限 <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 2. 配置本机蓝牙模块 在这里首先要了解对蓝牙操作一个核心类BluetoothAdapter BluetoothAdap

Android 蓝牙通信——AndroidBluetoothManager

转载请说明出处! 作者:kqw攻城狮 出处:个人站 | CSDN To get a Git project into your build: Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories: allprojects { repositories { ... maven { url 'https://jitpack.io

Android 蓝牙开发之搜索、配对、连接、通信大全

        蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最多可以同时和7个其它蓝牙设备建立连接,进 行通信,当然并不是每一个蓝牙都可以达到最大值.下面,我们从蓝牙的基本概念开始,一步一步开始了解蓝牙. 基本概念: 安卓平台提供对蓝牙的通讯栈的支持,允许设别和其他的设备进行无线传输数据.应用程序层通过安卓API来调用蓝牙的相关功 能,这些API使程序无线连接