Android 编程技巧之 ----- 蓝牙开发大全


原文出处 : Android 蓝牙开发之搜索、配对、连接、通信大全


蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据

交换(使用2.4—2.485GHz的ISM波段的UHF无线电波)。蓝牙设备最多可以同时和7个其它蓝牙设备建立连接,进

行通信,当然并不是每一个蓝牙都可以达到最大值。下面,我们从蓝牙的基本概念开始,一步一步开始了解蓝牙。

 

基本概念: 

         安卓平台提供对蓝牙的通讯栈的支持,允许设别和其他的设备进行无线传输数据。应用程序层通过安卓API来调用蓝牙的相关功

能,这些API使程序无线连接到蓝牙设备,并拥有P2P或者多端无线连接的特性。

 

蓝牙的功能:

1、扫描其他蓝牙设备

2、为可配对的蓝牙设备查询蓝牙适配器

3、建立RFCOMM通道

4、通过服务搜索来链接其他的设备

5、与其他的设备进行数据传输

6、管理多个连接



蓝牙建立连接必须要求:

1、打开蓝牙

2、查找附近已配对或可用设备

3、连接设备

4、设备间数据交换

 

 

常用的蓝牙API如下:

 

BluetoothAdapter

代表本地蓝牙适配器(蓝牙无线电)。BluetoothAdapter是所有蓝牙交互的入口。使用这个你可以发现其他蓝牙设备,查询已配对的设备列表,使用一个已知的MAC地址来实例化一个BluetoothDevice,以及创建一个BluetoothServerSocket来为监听与其他设备的通信。

 

BlueDevice代表一个远程蓝牙设备,使用这个来请求一个与远程设备的BluetoothSocket连接,或者查询关于设备名称、地址、类和连接状态等设备信息。
BluetoothSocket代表一个蓝牙socket的接口(和TCP Socket类似)。这是一个连接点,它允许一个应用与其他蓝牙设备通过InputStream和OutputStream交换数据。
BluetoothServerSocket代表一个开放的服务器socket,它监听接受的请求(与TCP ServerSocket类似)。为了连接两台Android设备,一个设备必须使用这个类开启一个服务器socket。当一个远程蓝牙设备开始一个和该设备的连接请求,BluetoothServerSocket将会返回一个已连接的BluetoothSocket,接受该连接。

 

BluetoothAdapter 中常用方法如下所示:

boolean cancelDiscovery()
Cancel the current device discovery process.
static boolean checkBluetoothAddress( String address)
Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"

Alphabetic characters must be uppercase to be valid.

void closeProfileProxy(int profile,  BluetoothProfile proxy)
Close the connection of the profile proxy to the Service.
boolean disable()
Turn off the local Bluetooth adapter—do not use without explicit user action to turn off Bluetooth.
boolean enable()
Turn on the local Bluetooth adapter—do not use without explicit user action to turn on Bluetooth.
String getAddress()
Returns the hardware address of the local Bluetooth adapter.
Set< BluetoothDevice> getBondedDevices()
Return the set of  BluetoothDevice objects that are bonded (paired) to the local adapter.
synchronized static  BluetoothAdapter getDefaultAdapter()
Get a handle to the default local Bluetooth adapter.
String getName()
Get the friendly Bluetooth name of the local Bluetooth adapter.
int getProfileConnectionState(int profile)
Get the current connection state of a profile.
boolean getProfileProxy( Context context,  BluetoothProfile.ServiceListener listener, int profile)
Get the profile proxy object associated with the profile.
BluetoothDevice getRemoteDevice(byte[] address)
Get a  BluetoothDevice object for the given Bluetooth hardware address.
BluetoothDevice getRemoteDevice( String address)
Get a  BluetoothDevice object for the given Bluetooth hardware address.
int getScanMode()
Get the current Bluetooth scan mode of the local Bluetooth adapter.
int getState()
Get the current state of the local Bluetooth adapter.
boolean isDiscovering()
Return true if the local Bluetooth adapter is currently in the device discovery process.
boolean isEnabled()
Return true if Bluetooth is currently enabled and ready for use.
BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord( String name,  UUID uuid)
Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
BluetoothServerSocket listenUsingRfcommWithServiceRecord( String name,  UUID uuid)
Create a listening, secure RFCOMM Bluetooth socket with Service Record.
boolean setName( String name)
Set the friendly Bluetooth name of the local Bluetooth adapter.
boolean startDiscovery()
Start the remote device discovery process.
boolean startLeScan( BluetoothAdapter.LeScanCallback callback)
Starts a scan for Bluetooth LE devices.
boolean startLeScan( UUID[] serviceUuids,  BluetoothAdapter.LeScanCallback callback)
Starts a scan for Bluetooth LE devices, looking for devices that advertise given services.
void stopLeScan( BluetoothAdapter.LeScanCallback callback)
Stops an ongoing Bluetooth LE device scan.

 

BluetoothDevice 中常用方法如下所示:

BluetoothGatt connectGatt( Context context, boolean autoConnect,  BluetoothGattCallback callback)
Connect to GATT Server hosted by this device.
boolean createBond()
Start the bonding (pairing) process with the remote device.
BluetoothSocket createInsecureRfcommSocketToServiceRecord( UUID uuid)
Create an RFCOMM  BluetoothSocket socket ready to start an insecure outgoing connection to this remote device using SDP lookup of uuid.
BluetoothSocket createRfcommSocketToServiceRecord( UUID uuid)
Create an RFCOMM  BluetoothSocket ready to start a secure outgoing connection to this remote device using SDP lookup of uuid.
int describeContents()
Describe the kinds of special objects contained in this Parcelable's marshalled representation.
boolean equals( Object o)
Compares this instance with the specified object and indicates if they are equal.
boolean fetchUuidsWithSdp()
Perform a service discovery on the remote device to get the UUIDs supported.
String getAddress()
Returns the hardware address of this BluetoothDevice.
BluetoothClass getBluetoothClass()
Get the Bluetooth class of the remote device.
int getBondState()
Get the bond state of the remote device.
String getName()
Get the friendly Bluetooth name of the remote device.
int getType()
Get the Bluetooth device type of the remote device.
ParcelUuid[] getUuids()
Returns the supported features (UUIDs) of the remote device.
int hashCode()
Returns an integer hash code for this object.
boolean setPairingConfirmation(boolean confirm)
Confirm passkey for  PAIRING_VARIANT_PASSKEY_CONFIRMATION pairing.
boolean setPin(byte[] pin)
Set the pin during pairing when the pairing method is  PAIRING_VARIANT_PIN

Requires BLUETOOTH_ADMIN.

String toString()
Returns a string representation of this BluetoothDevice.
void writeToParcel( Parcel out, int flags)
Flatten this object in to a Parcel.

 

BluetoothSocket 中常用方法如下所示:

void close()
Closes the object and release any system resources it holds.
void connect()
Attempt to connect to a remote device.
InputStream getInputStream()
Get the input stream associated with this socket.
OutputStream getOutputStream()
Get the output stream associated with this socket.
BluetoothDevice getRemoteDevice()
Get the remote device this socket is connecting, or connected, to.
boolean isConnected()
Get the connection status of this socket, ie, whether there is an active connection with remote device.

 

BluetoothServerSocket 中常用方法如下所示:

BluetoothSocket accept(int timeout)
Block until a connection is established, with timeout.
BluetoothSocket accept()
Block until a connection is established.
void close()
Immediately close this socket, and release all associated resources.

 

 以上四个类贯穿于我们蓝牙通信的全过程,包括蓝牙搜索、配对、连接以及通信。

 

 

使用蓝牙需要在配置文件Androidmanifest.xml 中注册两种权限:

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

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

其中,权限1在得到默认蓝牙适配器时需要,即BluetoothAdapter  mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter( )

权限2在mBluetoothAdapter.enable( )或者mBluetoothAdapter.disable( ) 时需要使用到。

 


 

 一、蓝牙搜索功能的实现:

 

1、得到蓝牙适配器:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. BluetoothAdapter mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();  

若mBluetoothAdapter为 null,则说明当前手机不支持蓝牙功能(现在几乎所有手机都支持了吧。。。)

 

2、判断蓝牙是否打开:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. if (!mBluetoothAdapter.isEnabled()) {  
  2.        //若没打开则打开蓝牙  
  3.        mBluetoothAdapter.enable();  
  4.     
  5. }  

值得注意的是,强制打开蓝牙设备的情况有三种:

(1)没有任何提示,直接打开了蓝牙。如Nexus 5 Android 4.4.4 手机。

(2)会弹出提示框,提示安全警告 “ ***应用尝试开启蓝牙”,可以选择“拒绝”或“允许”。大多数手机都是这样的。

(3)强制打开蓝牙失败,并且没有任何提示。

 

 

3、注册蓝牙搜索广播接收者:

(1)Android 的广播机制:

     Adnroid的广播机制(以intent对象的形式广播出去),Android系统广播的时候不会关心你是否收得到消息、只负责广播出去,而

且广播的对象只是在应用程序中注册了的广播接收器。我们要做的就是自定义广播接收器并将其注册给应用程序,在广播接收器中

将接收到广播事件作出相应的处理。如果广播的事件并不是我们定义的广播接收器需要的事件类型,一般是会过滤掉不被接收。只

有当广播事件和我们写的接收器定义的接收的事件类型一致的时候才会触发广播接收器。并且触发广播接收器的onReceive方法。当

然我们自定义的广播接收器需要接受事件的类型是在XML清单文件的<intent-filter>中自己定义声明的或者自己在程序代码中定义一

个IntentFilter对象然后通过对象的addAction()方法来自定义接收事件类型。然后我们需要将接收到的事件的处理代码写在onReceive

方法中。

(2)注册分为两种:静态注册和动态注册。

  • 静态注册就是在AndroidManifest.xml文件中定义,注册的广播接收器必须继承BroadReceiver
  • 动态注册就是在程序中使用Context.registerReceiver注册。

 

我们先演示动态注册:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //注册设备被发现时的广播  
  2. IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  3.         registerReceiver(mReceiver,filter);  
  4. //注册一个搜索结束时的广播  
  5. IntentFilter filter2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
  6.         registerReceiver(mReceiver,filter2);  


对应的静态注册如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 广播接收 -->  
  2.         <receiver android:name="包名.类名" >  
  3.             <intent-filter android:priority="1000">  
  4.                 <action android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED"/>  
  5.                 <action android:name="android.bluetooth.device.action.FOUND" />  
  6.             </intent-filter>  
  7.     </receiver>  


我们如何知道BluetoothAdapter.ACTION_DISCOVERY_FINISHED对应着android.bluetooth.adapter.action.DISCOVERY_FINISHED呢?

这就要看强大的API了。如图就是一种对应关系:

此处推荐别人上传的中文API:

                                  点我打开Android中文API

 

 

4、定义广播接收:

自定义的广播接收器对象必须要继承BroadcastReceiver,然后重写onReceive方法,处理接收的数据的代码就写在这个方法里面。

两种方法:

  • 自定义一个类实现BroadcastReceiver抽象类,并且实现其onReceiver(Context context, Intent intent )方法。
  • 直接new BroadcastReceiver()来搞定。

方法1如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class BluetoothReceiver extends BroadcastReceiver{  
  2.         @Override  
  3.     public void onReceive(Context context, Intent intent) {  
  4.   
  5.           ...................  
  6.        }  
  7.   
  8. }  

方法2如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //定义广播接收  
  2.    private BroadcastReceiver mReceiver=new BroadcastReceiver(){  
  3.   
  4.        @Override  
  5.        public void onReceive(Context context, Intent intent) {  
  6.              .......................  
  7.                   }  
  8.    };  


 5、开始广播:

       通过  mBluetoothAdapter.startDiscovery( ); 来开始广播。当广播的事件是我们刚刚注册的事件时就会触发广播接收器,并且触

发广播接收器中的onReceiver()方法。

 

6、解除注册:

通过 unregisterReceiver(mReceiver); 来解除刚刚的注册。

 

至此我们完成了蓝牙通信的第一步:蓝牙搜索。

下边给出一个完整Demo实例。

功能为:点击按钮将搜索附近的蓝牙设备,并且判断是否与本设备已经配对,分类显示。

代码如下:

mainActivity.Java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.administrator.myapplication;  
  2.   
  3. import android.bluetooth.BluetoothAdapter;  
  4. import android.bluetooth.BluetoothDevice;  
  5. import android.content.BroadcastReceiver;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.content.IntentFilter;  
  9. import android.support.v7.app.AppCompatActivity;  
  10. import android.os.Bundle;  
  11. import android.util.Log;  
  12. import android.view.View;  
  13. import android.widget.Button;  
  14. import android.widget.TextView;  
  15. import android.widget.Toast;  
  16.   
  17. public class MainActivity extends AppCompatActivity {  
  18.   
  19.     //定义  
  20.     private BluetoothAdapter mBluetoothAdapter;  
  21.     private TextView text,text2,text3;  
  22.     private Button botton;  
  23.   
  24.     @Override  
  25.     protected void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.activity_main);  
  28.   
  29.   
  30.         text=(TextView) this.findViewById(R.id.textView);  //已配对  
  31.         text2= (TextView) this.findViewById(R.id.textView2); //状态信息  
  32.         text3= (TextView) this.findViewById(R.id.textView3); //未配对  
  33.         botton=(Button) this.findViewById(R.id.button);  
  34.   
  35.         mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();  
  36.   
  37.         IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  38.         registerReceiver(mReceiver,filter);  
  39.         IntentFilter filter2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
  40.         registerReceiver(mReceiver,filter2);  
  41.   
  42.         botton.setOnClickListener(new View.OnClickListener(){  
  43.   
  44.             @Override  
  45.             public void onClick(View arg0) {  
  46.   
  47.                 if(!mBluetoothAdapter.isEnabled())  
  48.                 {  
  49.                     mBluetoothAdapter.enable();  
  50.   
  51.                 }  
  52.   
  53.                     mBluetoothAdapter.startDiscovery();  
  54.                     text2.setText("正在搜索...");  
  55.   
  56.             }  
  57.   
  58.   
  59.         });  
  60.   
  61.   
  62.     }  
  63.   
  64.   
  65.     public void onDestroy() {  
  66.   
  67.         super.onDestroy();  
  68.         //解除注册  
  69.         unregisterReceiver(mReceiver);  
  70.         Log.e("destory","解除注册");  
  71.     }  
  72.   
  73.   
  74.   
  75.     //定义广播接收  
  76.     private BroadcastReceiver mReceiver=new BroadcastReceiver(){  
  77.   
  78.   
  79.   
  80.         @Override  
  81.         public void onReceive(Context context, Intent intent) {  
  82.   
  83.             String action=intent.getAction();  
  84.   
  85.             Log.e("ywq", action);  
  86.             if(action.equals(BluetoothDevice.ACTION_FOUND))  
  87.             {  
  88.                 BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  89.   
  90.                 if(device.getBondState()==BluetoothDevice.BOND_BONDED)  
  91.                 {    //显示已配对设备  
  92.                     text.append("\n"+device.getName()+"==>"+device.getAddress()+"\n");  
  93.                 }else if(device.getBondState()!=BluetoothDevice.BOND_BONDED)  
  94.                 {  
  95.                     text3.append("\n"+device.getName()+"==>"+device.getAddress()+"\n");  
  96.                 }  
  97.   
  98.             }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){  
  99.   
  100.                 text2.setText("搜索完成...");  
  101.   
  102.   
  103.             }  
  104.   
  105.         }  
  106.   
  107.   
  108.     };  
  109.   
  110. }  


AndroidManifest.xml代码如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.administrator.myapplication">  
  4.   
  5.     <uses-permission android:name="android.permission.BLUETOOTH" />  
  6.     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  
  7.   
  8.     <application  
  9.         android:allowBackup="true"  
  10.         android:icon="@mipmap/ic_launcher"  
  11.         android:label="@string/app_name"  
  12.         android:supportsRtl="true"  
  13.         android:theme="@style/AppTheme">  
  14.         <activity android:name=".MainActivity">  
  15.             <intent-filter>  
  16.                 <action android:name="android.intent.action.MAIN" />  
  17.   
  18.                 <category android:name="android.intent.category.LAUNCHER" />  
  19.             </intent-filter>  
  20.         </activity>  
  21.     </application>  
  22.   
  23. </manifest>  

 

布局文件activity_main.xml代码如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:id="@+id/activity_main"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     tools:context="com.example.administrator.myapplication.MainActivity">  
  12.   
  13.     <Button  
  14.         android:text="搜索蓝牙"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:layout_marginTop="19dp"  
  18.         android:id="@+id/button"  
  19.         android:layout_alignParentLeft="true"  
  20.         android:layout_alignParentStart="true" />  
  21.   
  22.     <TextView  
  23.         android:text="初始状态"  
  24.         android:layout_width="wrap_content"  
  25.         android:layout_height="wrap_content"  
  26.         android:layout_alignBottom="@+id/button"  
  27.         android:layout_toRightOf="@+id/button"  
  28.         android:layout_toEndOf="@+id/button"  
  29.         android:layout_marginLeft="45dp"  
  30.         android:layout_marginStart="45dp"  
  31.         android:layout_marginBottom="14dp"  
  32.         android:id="@+id/textView2" />  
  33.   
  34.     <TextView  
  35.         android:layout_width="wrap_content"  
  36.         android:layout_height="wrap_content"  
  37.         android:id="@+id/textView"  
  38.         android:text="已配对蓝牙设备如下:"  
  39.         android:layout_marginLeft="12dp"  
  40.         android:layout_marginStart="12dp"  
  41.         android:layout_marginTop="53dp"  
  42.         android:layout_below="@+id/button"  
  43.         android:layout_alignParentLeft="true"  
  44.         android:layout_alignParentStart="true" />  
  45.   
  46.     <TextView  
  47.         android:text="未配对蓝牙设备如下:"  
  48.         android:layout_width="wrap_content"  
  49.         android:layout_height="wrap_content"  
  50.         android:layout_marginTop="107dp"  
  51.         android:id="@+id/textView3"  
  52.         android:layout_below="@+id/textView"  
  53.         android:layout_alignLeft="@+id/textView"  
  54.         android:layout_alignStart="@+id/textView" />  
  55.   
  56. </RelativeLayout>  


程序运行结果如下:


 

 

二、蓝牙自动配对功能实现:

 

蓝牙配对是建立连接的基础和前提。为什么不配对便无法建立连接?

        任何无线通信技术都存在被监听和破解的可能,蓝牙SIG为了保证蓝牙通信的安全性,采用认证的方式进行数据交互。同时为

了保证使用的方便性,以配对的形式完成两个蓝牙设备之间的首次通讯认证,经配对之后,随后的通讯连接就不必每次都要做确

认。所以认证码的产生是从配对开始的,经过配对,设备之间以PIN码建立约定的link key用于产生初始认证码,以用于以后建立的

连接。

       所以如果不配对,两个设备之间便无法建立认证关系,无法进行连接及其之后的操作,所以配对在一定程度上保证了蓝牙通信

的安全,当然这个安全保证机制是比较容易被破解的,因为现在很多个人设备没有人机接口,所以PIN码都是固定的而且大都设置为

通用的0000或者1234之类的,所以很容易被猜到并进而建立配对和连接。

 

关于蓝牙的自动配对,大家可以参考我的这篇博客:Android蓝牙自动配对Demo,亲测好使!!!

这里自夸一下,这篇博客还是受到了大家的一些好评。该自动配对方法,博主在魅蓝、华为、联想、红米以及Nexus手机上都有测

试过,使用的Android系统包括4.0+和5.0+,所以各位可以仔细阅读该博客。

 

 

 

三、蓝牙通信的实现:

 

本文所述的蓝牙通信为:Android 端蓝牙设备与其他蓝牙设备之间的通信

 

   下边讲述  Android手机端蓝牙与Arduino外接蓝牙模块之间进行通信。

 

(1)Arduino 端蓝牙模块

        蓝牙模块在Arduino 端只是一个串口,将蓝牙模块的Tx、Rx接在Arduino开发板上。

        初始化与Android蓝牙通信的串口,使用串口.read()来读取来自手机蓝牙的信息;使用串口.println(“XXXXXX”)来向手机

端蓝牙发送信息。

 

Demo代码如下:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. void setup() {  
  2.  Serial.begin(9600);   //初始化原有串口  
  3.   
  4.  SerialBT.begin(9600);  //初始化一个串口用来作为蓝牙通信  
  5.   
  6. }  
  7.   
  8. void loop() {  
  9.   
  10.  if(SerialBT.available()){  //如果串口可用,即串口中有数据传过来  
  11.       char rece=SerialBT.read();   //rece是来自手机蓝牙的信息  
  12.       Serial.println("已经接收到来自Android蓝牙的信息"); //这句话将打印在Arduino自带的串口监视窗里  
  13.   if(rece=='A'){  
  14.        SerialBT.println("这是来自Arduino的信息");   //这句话的内容将显示在Android手机端  
  15.     }  
  16.     
  17.   }  
  18.   
  19. }  


(2)手机端蓝牙模块:

 Demo运行结果如下所示:

 

 

Demo代码如下:

MainActivity.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.ywq;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.util.UUID;  
  7. import com.example.alltest.R;  
  8. import android.os.AsyncTask;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.app.Activity;  
  13. import android.bluetooth.BluetoothAdapter;  
  14. import android.bluetooth.BluetoothDevice;  
  15. import android.bluetooth.BluetoothSocket;  
  16. import android.util.Log;  
  17. import android.view.Menu;  
  18. import android.view.View;  
  19. import android.widget.Button;  
  20. import android.widget.EditText;  
  21. import android.widget.TextView;  
  22. import android.widget.Toast;  
  23.   
  24. public class MainActivity extends Activity {  
  25.   
  26.     //定义组件  
  27.     TextView statusLabel;   
  28.     Button btnConnect,btnSend,btnQuit;  
  29.     EditText etReceived,etSend;  
  30.       
  31.     //device var  
  32.     private BluetoothAdapter mBluetoothAdapter = null;    
  33.         
  34.     private BluetoothSocket btSocket = null;    
  35.        
  36.     private OutputStream outStream = null;    
  37.             
  38.     private InputStream inStream = null;    
  39.     
  40.     //这条是蓝牙串口通用的UUID,不要更改    
  41.     private static final UUID MY_UUID =   
  42.             UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");    
  43.         
  44.     private static String address = "20:16:07:26:18:46"// <==要连接的目标蓝牙设备MAC地址    
  45.   
  46.       
  47.     private ReceiveThread rThread=null;  //数据接收线程  
  48.       
  49.     //接收到的字符串  
  50.     String ReceiveData="";  
  51.       
  52.     MyHandler handler;  
  53.       
  54.       
  55.         
  56.     @Override  
  57.     protected void onCreate(Bundle savedInstanceState) {  
  58.         super.onCreate(savedInstanceState);  
  59.         setContentView(R.layout.activity_main);  
  60.         //首先调用初始化函数  
  61.         Init();   
  62.         InitBluetooth();  
  63.           
  64.         handler=new MyHandler();          
  65.           
  66.         btnConnect.setOnClickListener(new View.OnClickListener() {    
  67.             @Override  
  68.             public void onClick(View v) {  
  69.                 //判断蓝牙是否打开  
  70.                 if(!mBluetoothAdapter.isEnabled())     
  71.                 {    
  72.                    mBluetoothAdapter.enable();  
  73.                 }  
  74.                  mBluetoothAdapter.startDiscovery();                  
  75.       
  76.             //创建连接    
  77.             new ConnectTask().execute(address);  
  78.                   
  79.             }  
  80.         });  
  81.           
  82.           
  83.         btnQuit.setOnClickListener(new View.OnClickListener() {  
  84.               
  85.             @Override  
  86.             public void onClick(View v) {  
  87.                 // TODO Auto-generated method stub  
  88.                   
  89.                 if(btSocket!=null)  
  90.                 {  
  91.                     try {  
  92.                         btSocket.close();  
  93.                         btSocket=null;  
  94.                         if(rThread!=null)  
  95.                         {  
  96.                             rThread.join();  
  97.                         }     
  98.                         statusLabel.setText("当前连接已断开");  
  99. //                      etReceived.setText("");  
  100.                     } catch (IOException e) {  
  101.                           
  102.                         e.printStackTrace();  
  103.                     } catch (InterruptedException e) {  
  104.   
  105.                         e.printStackTrace();  
  106.                     }  
  107.                 }  
  108.                   
  109.                   
  110.                   
  111.             }  
  112.         });  
  113.           
  114.         btnSend.setOnClickListener(new View.OnClickListener() {  
  115.               
  116.             @Override  
  117.             public void onClick(View v) {  
  118.                 // TODO Auto-generated method stub  
  119.                 new SendInfoTask().execute(etSend.getText().toString());  
  120.                                   
  121.             }  
  122.         });  
  123.     }  
  124.           
  125.     public void Init()  
  126.     {  
  127.         statusLabel=(TextView)this.findViewById(R.id.textView1);  
  128.         btnConnect=(Button)this.findViewById(R.id.button1);  
  129.         btnSend=(Button)this.findViewById(R.id.button2);  
  130.         btnQuit=(Button)this.findViewById(R.id.button3);  
  131.         etSend=(EditText)this.findViewById(R.id.editText1);  
  132.         etReceived=(EditText)this.findViewById(R.id.editText2);  
  133.     }  
  134.   
  135.     public void InitBluetooth()  
  136.     {  
  137.         //得到一个蓝牙适配器  
  138.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
  139.             if(mBluetoothAdapter == null)     
  140.                 {    
  141.                     Toast.makeText(this"你的手机不支持蓝牙", Toast.LENGTH_LONG).show();    
  142.                     finish();    
  143.                     return;    
  144.                 }    
  145.   
  146.     }  
  147.       
  148.     @Override  
  149.     public boolean onCreateOptionsMenu(Menu menu) {  
  150.         // Inflate the menu; this adds items to the action bar if it is present.  
  151.         getMenuInflater().inflate(R.menu.main, menu);  
  152.         return true;  
  153.     }  
  154.       
  155.     //连接蓝牙设备的异步任务  
  156.     class ConnectTask extends AsyncTask<String,String,String>  
  157.         {  
  158.               
  159.   
  160.             @Override  
  161.             protected String doInBackground(String... params) {  
  162.                 // TODO Auto-generated method stub  
  163.              BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(params[0]);    
  164.                    
  165.                     try {    
  166.                 
  167.                         btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);    
  168.             
  169.                             
  170.                         btSocket.connect();    
  171.                 
  172.                         Log.e("error""ON RESUME: BT connection established, data transfer link open.");    
  173.                 
  174.                     } catch (IOException e) {    
  175.                
  176.                        try {    
  177.                             btSocket.close();   
  178.                             return "Socket 创建失败";  
  179.         
  180.                         } catch (IOException e2) {    
  181.                               
  182.                            Log .e("error","ON RESUME: Unable to close socket during connection failure", e2);  
  183.                            return "Socket 关闭失败";  
  184.                        }    
  185.                 
  186.                     }   
  187.                     //取消搜索  
  188.                     mBluetoothAdapter.cancelDiscovery();    
  189.                       
  190.                     try {   
  191.                          outStream = btSocket.getOutputStream();   
  192.                                              
  193.                        } catch (IOException e) {   
  194.                          Log.e("error""ON RESUME: Output stream creation failed.", e);  
  195.                          return "Socket 流创建失败";  
  196.                        }   
  197.                         
  198.                       
  199.                     return "蓝牙连接正常,Socket 创建成功";  
  200.             }  
  201.   
  202.             @Override    //这个方法是在主线程中运行的,所以可以更新界面  
  203.             protected void onPostExecute(String result) {  
  204.                 // TODO Auto-generated method stub  
  205.                   
  206.                 //连接成功则启动监听   
  207.                 rThread=new ReceiveThread();  
  208.                   
  209.                 rThread.start();  
  210.                   
  211.                 statusLabel.setText(result);  
  212.                   
  213.                 super.onPostExecute(result);  
  214.             }  
  215.               
  216.               
  217.               
  218.         }  
  219.       
  220.     //发送数据到蓝牙设备的异步任务  
  221.     class SendInfoTask extends AsyncTask<String,String,String>  
  222.     {  
  223.   
  224.         @Override  
  225.         protected void onPostExecute(String result) {  
  226.             // TODO Auto-generated method stub  
  227.             super.onPostExecute(result);  
  228.               
  229.             statusLabel.setText(result);  
  230.               
  231.             //将发送框清空  
  232.             etSend.setText("");  
  233.         }  
  234.   
  235.         @Override  
  236.         protected String doInBackground(String... arg0) {  
  237.             // TODO Auto-generated method stub  
  238.               
  239.             if(btSocket==null)  
  240.             {  
  241.                 return "还没有创建连接";  
  242.             }  
  243.               
  244.             if(arg0[0].length()>0)//不是空白串  
  245.             {  
  246.                      //String target=arg0[0];  
  247.               
  248.                       byte[] msgBuffer = arg0[0].getBytes();   
  249.                   
  250.                       try {   
  251.                       //  将msgBuffer中的数据写到outStream对象中  
  252.                       outStream.write(msgBuffer);   
  253.                    
  254.                        } catch (IOException e) {   
  255.                            Log.e("error""ON RESUME: Exception during write.", e);  
  256.                            return "发送失败";  
  257.                    }   
  258.   
  259.             }  
  260.               
  261.             return "发送成功";  
  262.         }  
  263.           
  264.     }  
  265.       
  266.       
  267.     //从蓝牙接收信息的线程  
  268.     class ReceiveThread extends Thread  
  269.     {  
  270.   
  271.         String buffer="";  
  272.           
  273.         @Override  
  274.         public void run() {  
  275.               
  276.             while(btSocket!=null )  
  277.             {        
  278.                     //定义一个存储空间buff  
  279.                     byte[] buff=new byte[1024];  
  280.                     try {  
  281.                         inStream = btSocket.getInputStream();   
  282.                         System.out.println("waitting for instream");   
  283.                         inStream.read(buff); //读取数据存储在buff数组中  
  284. //                        System.out.println("buff receive :"+buff.length);  
  285.                           
  286.                             
  287.                          processBuffer(buff,1024);   
  288.                            
  289.                         //System.out.println("receive content:"+ReceiveData);  
  290.                     } catch (IOException e) {  
  291.                           
  292.                         e.printStackTrace();  
  293.                     }  
  294.             }         
  295.         }     
  296.           
  297.         private void processBuffer(byte[] buff,int size)  
  298.         {  
  299.             int length=0;  
  300.             for(int i=0;i<size;i++)  
  301.             {  
  302.                 if(buff[i]>'\0')  
  303.                 {  
  304.                     length++;  
  305.                 }  
  306.                 else  
  307.                 {  
  308.                     break;  
  309.                 }  
  310.             }  
  311.               
  312. //          System.out.println("receive fragment size:"+length);   
  313.               
  314.             byte[] newbuff=new byte[length];  //newbuff字节数组,用于存放真正接收到的数据  
  315.               
  316.             for(int j=0;j<length;j++)  
  317.             {  
  318.                 newbuff[j]=buff[j];  
  319.             }         
  320.               
  321.             ReceiveData=ReceiveData+new String(newbuff);  
  322.             Log.e("Data",ReceiveData);  
  323. //          System.out.println("result :"+ReceiveData);  
  324.                         Message msg=Message.obtain();  
  325.             msg.what=1;   
  326.             handler.sendMessage(msg);  //发送消息:系统会自动调用handleMessage( )方法来处理消息    
  327.               
  328.         }  
  329.           
  330.     }  
  331.       
  332.   
  333.       
  334.     //更新界面的Handler类  
  335.     class MyHandler extends Handler{  
  336.   
  337.         @Override  
  338.         public void handleMessage(Message msg) {  
  339.   
  340.             switch(msg.what){  
  341.             case 1:  
  342.                 etReceived.setText(ReceiveData);  
  343.                 break;  
  344.             }  
  345.         }     
  346.     }  
  347.   
  348.     @Override  
  349.     protected void onDestroy() {  
  350.         // TODO Auto-generated method stub  
  351.         super.onDestroy();  
  352.           
  353.         try {  
  354.             if(rThread!=null)  
  355.             {  
  356.                   
  357.                 btSocket.close();  
  358.                 btSocket=null;  
  359.                   
  360.                 rThread.join();  
  361.             }  
  362.               
  363.             this.finish();  
  364.               
  365.         } catch (IOException e) {  
  366.             // TODO Auto-generated catch block  
  367.             e.printStackTrace();  
  368.         } catch (InterruptedException e) {  
  369.             // TODO Auto-generated catch block  
  370.             e.printStackTrace();  
  371.         }         
  372.           
  373.     }  
  374.   
  375. }  

 

BluetoothReceiver.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.ywq.broadcast;  
  2.   
  3. import com.ywq.tools.ClsUtils;  
  4. import android.bluetooth.BluetoothDevice;  
  5. import android.content.BroadcastReceiver;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.util.Log;  
  9.   
  10.   
  11. public class BluetoothReceiver extends BroadcastReceiver{  
  12.   
  13.     String pin = "1234";  //此处为你要连接的蓝牙设备的初始密钥,一般为1234或0000  
  14.     public BluetoothReceiver() {  
  15.           
  16.     }  
  17.   
  18.     //广播接收器,当远程蓝牙设备被发现时,回调函数onReceiver()会被执行   
  19.     @Override  
  20.     public void onReceive(Context context, Intent intent) {  
  21.           
  22.         String action = intent.getAction(); //得到action  
  23.         Log.e("action1=", action);  
  24.         BluetoothDevice btDevice=null;  //创建一个蓝牙device对象  
  25.          // 从Intent中获取设备对象  
  26.         btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);   
  27.           
  28.         if(BluetoothDevice.ACTION_FOUND.equals(action)){  //发现设备  
  29.             Log.e("发现设备:""["+btDevice.getName()+"]"+":"+btDevice.getAddress());  
  30.               
  31.             if(btDevice.getName().contains("HC-05"))//HC-05设备如果有多个,第一个搜到的那个会被尝试。  
  32.             {  
  33.                 if (btDevice.getBondState() == BluetoothDevice.BOND_NONE) {    
  34.                       
  35.                     Log.e("ywq""attemp to bond:"+"["+btDevice.getName()+"]");  
  36.                     try {  
  37.                         //通过工具类ClsUtils,调用createBond方法  
  38.                         ClsUtils.createBond(btDevice.getClass(), btDevice);  
  39.                     } catch (Exception e) {  
  40.                         // TODO Auto-generated catch block  
  41.                         e.printStackTrace();  
  42.                     }  
  43.                 }  
  44.             }else  
  45.                 Log.e("error""Is faild");  
  46.         }else if(action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) //再次得到的action,会等于PAIRING_REQUEST  
  47.         {  
  48.             Log.e("action2=", action);  
  49.             if(btDevice.getName().contains("HC-05"))  
  50.             {  
  51.                 Log.e("here""OKOKOK");  
  52.                   
  53.                 try {  
  54.                       
  55.                     //1.确认配对  
  56.                     ClsUtils.setPairingConfirmation(btDevice.getClass(), btDevice, true);  
  57.                     //2.终止有序广播  
  58.                     Log.i("order...""isOrderedBroadcast:"+isOrderedBroadcast()+",isInitialStickyBroadcast:"+isInitialStickyBroadcast());  
  59.                     abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。  
  60.                     //3.调用setPin方法进行配对...  
  61.                     boolean ret = ClsUtils.setPin(btDevice.getClass(), btDevice, pin);  
  62.                   
  63.                 } catch (Exception e) {  
  64.                     // TODO Auto-generated catch block  
  65.                     e.printStackTrace();  
  66.                 }  
  67.             }else  
  68.                 Log.e("提示信息""这个设备不是目标蓝牙设备");  
  69.               
  70.         }  
  71.     }  
  72. }  


配对工具类ClsUtils.java如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.ywq.tools;  
  2.   
  3. /************************************ 蓝牙配对函数 * **************/  
  4.   
  5. import java.lang.reflect.Method;    
  6. import java.lang.reflect.Field;    
  7. import android.bluetooth.BluetoothDevice;    
  8. import android.util.Log;    
  9.     
  10. public class ClsUtils     
  11. {    
  12.     /**  
  13.      * 与设备配对 参考源码:platform/packages/apps/Settings.git  
  14.      * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java  
  15.      */    
  16.     static public boolean createBond(Class btClass, BluetoothDevice btDevice)    
  17.     throws Exception    
  18.     {    
  19.         Method createBondMethod = btClass.getMethod("createBond");    
  20.         Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);    
  21.         return returnValue.booleanValue();    
  22.     }    
  23.      
  24.     /**  
  25.      * 与设备解除配对 参考源码:platform/packages/apps/Settings.git  
  26.      * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java  
  27.      */    
  28.     static public boolean removeBond(Class<?> btClass, BluetoothDevice btDevice)    
  29.             throws Exception    
  30.     {    
  31.         Method removeBondMethod = btClass.getMethod("removeBond");    
  32.         Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);    
  33.         return returnValue.booleanValue();    
  34.     }    
  35.      
  36.     static public boolean setPin(Class<? extends BluetoothDevice> btClass, BluetoothDevice btDevice,    
  37.             String str) throws Exception    
  38.     {    
  39.         try    
  40.         {    
  41.             Method removeBondMethod = btClass.getDeclaredMethod("setPin",    
  42.                     new Class[]    
  43.                     {byte[].class});    
  44.             Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,    
  45.                     new Object[]    
  46.                     {str.getBytes()});    
  47.             Log.e("returnValue""" + returnValue);    
  48.         }    
  49.         catch (SecurityException e)    
  50.         {    
  51.             // throw new RuntimeException(e.getMessage());    
  52.             e.printStackTrace();    
  53.         }    
  54.         catch (IllegalArgumentException e)    
  55.         {    
  56.             // throw new RuntimeException(e.getMessage());    
  57.             e.printStackTrace();    
  58.         }    
  59.         catch (Exception e)    
  60.         {    
  61.             // TODO Auto-generated catch block    
  62.             e.printStackTrace();    
  63.         }    
  64.         return true;    
  65.      
  66.     }    
  67.      
  68.     // 取消用户输入    
  69.     static public boolean cancelPairingUserInput(Class<?> btClass,    
  70.             BluetoothDevice device)  throws Exception    
  71.     {    
  72.         Method createBondMethod = btClass.getMethod("cancelPairingUserInput");    
  73. //        cancelBondProcess(btClass, device);  
  74.         Boolean returnValue = (Boolean) createBondMethod.invoke(device);    
  75.         return returnValue.booleanValue();    
  76.     }    
  77.      
  78.     // 取消配对    
  79.     static public boolean cancelBondProcess(Class<?> btClass,    
  80.             BluetoothDevice device)    
  81.      
  82.     throws Exception    
  83.     {    
  84.         Method createBondMethod = btClass.getMethod("cancelBondProcess");    
  85.         Boolean returnValue = (Boolean) createBondMethod.invoke(device);    
  86.         return returnValue.booleanValue();    
  87.     }   
  88.       
  89.     //确认配对  
  90.       
  91.     static public void setPairingConfirmation(Class<?> btClass,BluetoothDevice device,boolean isConfirm)throws Exception   
  92.     {  
  93.         Method setPairingConfirmation = btClass.getDeclaredMethod("setPairingConfirmation",boolean.class);   
  94.         setPairingConfirmation.invoke(device,isConfirm);  
  95.     }  
  96.       
  97.      
  98.     /**  
  99.      *  
  100.      * @param clsShow  
  101.      */    
  102.     static public void printAllInform(Class clsShow)    
  103.     {    
  104.         try    
  105.         {    
  106.             // 取得所有方法    
  107.             Method[] hideMethod = clsShow.getMethods();    
  108.             int i = 0;    
  109.             for (; i < hideMethod.length; i++)    
  110.             {    
  111.                 Log.e("method name", hideMethod[i].getName() + ";and the i is:"    
  112.                         + i);    
  113.             }  
  114.             // 取得所有常量    
  115.             Field[] allFields = clsShow.getFields();    
  116.             for (i = 0; i < allFields.length; i++)    
  117.             {    
  118.                 Log.e("Field name", allFields[i].getName());    
  119.             }  
  120.         }    
  121.         catch (SecurityException e)    
  122.         {    
  123.             // throw new RuntimeException(e.getMessage());    
  124.             e.printStackTrace();    
  125.         }    
  126.         catch (IllegalArgumentException e)    
  127.         {    
  128.             // throw new RuntimeException(e.getMessage());    
  129.             e.printStackTrace();    
  130.         }    
  131.         catch (Exception e)    
  132.         {    
  133.             // TODO Auto-generated catch block    
  134.             e.printStackTrace();    
  135.         }    
  136.     }    
  137. }    


配置文件AndroidManifest.xml如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.alltest"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="21" />  
  10.       
  11.     <!-- 蓝牙使用权限 -->  
  12.     <uses-permission android:name="android.permission.BLUETOOTH"/>  
  13.     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>  
  14.       
  15.       
  16.     <application  
  17.         android:allowBackup="true"  
  18.         android:icon="@drawable/ic_launcher"  
  19.         android:label="@string/app_name"  
  20.         android:theme="@style/AppTheme" >  
  21.           
  22.         <activity  
  23.             android:name="com.ywq.MainActivity"  
  24.             android:label="@string/app_name" >  
  25.             <intent-filter>  
  26.                 <action android:name="android.intent.action.MAIN" />  
  27.                 <category android:name="android.intent.category.LAUNCHER" />  
  28.             </intent-filter>  
  29.         </activity>  
  30.           
  31.         <!-- 广播接收 -->  
  32.         <receiver android:name="com.ywq.broadcast.BluetoothReceiver" >  
  33.             <intent-filter android:priority="1000">  
  34.                 <action android:name="android.bluetooth.device.action.PAIRING_REQUEST"/>  
  35.                 <action android:name="android.bluetooth.device.action.FOUND" />  
  36.             </intent-filter>  
  37.         </receiver>  
  38.           
  39.     </application>  
  40.    
  41. </manifest>  


布局文件如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:id="@+id/LinearLayout1"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="vertical"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     tools:context=".MainActivity" >  
  12.          
  13.     <LinearLayout  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content" >  
  16.   
  17.         <Button  
  18.             android:id="@+id/button1"  
  19.             android:layout_width="wrap_content"  
  20.             android:layout_height="wrap_content"  
  21.             android:text="连接" />  
  22.           
  23.   
  24.         <TextView  
  25.             android:id="@+id/textView1"  
  26.             android:layout_width="wrap_content"  
  27.             android:layout_height="wrap_content"  
  28.             android:text="当前没有连接任何设备" />  
  29.   
  30.     </LinearLayout>  
  31.   
  32.     <LinearLayout  
  33.         android:layout_width="match_parent"  
  34.         android:layout_height="wrap_content" >  
  35.   
  36.         <EditText  
  37.             android:id="@+id/editText1"  
  38.             android:layout_width="wrap_content"  
  39.             android:layout_height="wrap_content"  
  40.             android:layout_weight="1"  
  41.             android:ems="10" >  
  42.   
  43.             <requestFocus />  
  44.         </EditText>  
  45.   
  46.         <Button  
  47.             android:id="@+id/button2"  
  48.             android:layout_width="wrap_content"  
  49.             android:layout_height="wrap_content"  
  50.             android:layout_weight="1"  
  51.             android:text="发送" />  
  52.   
  53.     </LinearLayout>  
  54.   
  55.     <LinearLayout  
  56.         android:layout_width="match_parent"  
  57.         android:layout_height="wrap_content" >  
  58.   
  59.         <TextView  
  60.             android:id="@+id/textView2"  
  61.             android:layout_width="wrap_content"  
  62.             android:layout_height="wrap_content"  
  63.             android:text="接收到的数据" />  
  64.   
  65.     </LinearLayout>  
  66.   
  67.     <LinearLayout  
  68.         android:layout_width="match_parent"  
  69.         android:layout_height="wrap_content" >  
  70.   
  71.         <EditText  
  72.             android:id="@+id/editText2"  
  73.             android:layout_width="wrap_content"  
  74.             android:layout_height="300dp"  
  75.             android:layout_weight="1"  
  76.             android:ems="10"  
  77.             android:inputType="textMultiLine" />  
  78.   
  79.     </LinearLayout>  
  80.   
  81.     <LinearLayout  
  82.         android:layout_width="match_parent"  
  83.         android:layout_height="wrap_content" >  
  84.   
  85.         <Button  
  86.             android:id="@+id/button3"  
  87.             android:layout_width="wrap_content"  
  88.             android:layout_height="wrap_content"  
  89.             android:text="断开连接" />  
  90.   
  91.     </LinearLayout>  
  92.   
  93. </LinearLayout>  


 程序分析:

       程序主要分为:自动配对==>>建立连接==>>开启线程监听是否收到信息==>>向Arduino 端发送信息==>>断开连接


 自动配对:通过mBluetoothAdapter.startDiscovery();来实现。我们来看一下API中对该方法的描述:

 

public boolean startDiscovery ()

开始对远程设备进行查找的进程

它通常牵涉到一个大概需时12秒的查询扫描过程,紧跟着是一个对每个获取到自身蓝牙名称的新设备的页面扫描。

这是一个异步调用方法:该方法将马上获得返回值,注册ACTION_DISCOVERY_STARTED and

ACTION_DISCOVERY_FINISHED意图准确地确定该探索是处于开始阶段或者完成阶段。注册ACTION_FOUND以活动远程蓝牙设

备 已找到的通知。

设备查找是一个重量级过程。当查找正在进行的时候,用户不能尝试对新的远程蓝牙设备进行连接,同时存在的连接将获得有限制

的带宽以 及高等待时间。用户可用cencelDiscovery()类来取消正在执行的查找进程。发现的过程不会由活动来进行管理,但是它会

作为一个系统服务来运 行,因此即使它不能直接请求这样的一个查询动作,也必需取消该搜索进程。

设备搜寻只寻找已经被连接的远程设备。许多蓝牙设备默认不会被搜寻到,并且需要进入到一个特殊的模式当中。

如果蓝牙状态不是STATE_ON,这个API将返回false。蓝牙打开后,等待ACTION_STATE_CHANGED更新成STATE_ON。

需要BLUETOOTH_ADMIN权限。

返回值

成功返回true,错误返回false。

 

 由上面我们可以看出,当调用该方法并且发现设备时,将执行我们自定义的广播接收类中的onReceiver()会被执行,实现自动配对具体可以参考:

                                                                    Android蓝牙自动配对Demo,亲测好使!!!


建立连接:使用了一个异步AsyncTask任务。关于AsyncTask的使用,可以参考本博客:

                                                                                android AsyncTask介绍 

 我们首先利用远程蓝牙的mac地址得到了远程蓝牙设备:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);  

其次利用UUID得到了一个BluetoothSocket对象:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);   

然后调用connect()方法建立了socket连接

最后通过:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. mBluetoothAdapter.cancelDiscovery();  

来取消了搜索。



开启线程,监听输入:当socket创建成功后,需要监听输入。

我们首先通过BluetoothSocket对象得到输入流。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. inStream = btSocket.getInputStream();   

通过read()方法来读取来自Arduino端的信息。其中,read()方法是一个可以阻塞的方法。阻塞的意思是,当输入流中没有数据

传来时,该方法被阻塞,程序不会执行下边的内容,直到有数据传来。

如果有数据传来,则通过Message和Handler来更新UI,实现数据的显示。

 

向Arduino发送信息:同样适用了AsyncTask类来实现,  android AsyncTask介绍  。

当我们点击发送按钮时,首先判断socket是否成功创建,成功则使用输出流发送信息。否则,给出提示。


 断开连接:

首先我们需要通过btSocket.close( )来关闭socket,然后调用线程的join( )来将线程停止。实现了蓝牙之间的断开连接操作。

 

 

 

 至此,我们学习了Android蓝牙的搜索、配对、连接、通信,对蓝牙开发有了一个较为初步的认识。


  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值