android蓝牙开发

Home / Android MrLee 2015-4-28 4574

090522_bluetooth


检查设备是否支持蓝牙 实现步骤:
判断是否有蓝牙设备。 是否开启蓝牙。 若没有开启则请求开启蓝牙。 操作需要权限 :
1
2
3
4
5
6
7
8
9
10
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter(); 
    if(null!=ba){ 
        System.out.println("本机有蓝牙设备"); 
                   
        if(!ba.isEnabled()){ 
            Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
            startActivity(intent);  //或者ba.enable();  //同样的关闭WIFi为ba.disable(); 
    }else{
         System.out.println("本机没有蓝牙设备"); 
    }
设置蓝牙的可见时间(允许其他设备搜索到) 实现步骤: 设置蓝牙的可见时间 需要权限:
1
2
3
4
5
Intent intentvisible=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
           
intentvisible.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 400); 
//这个值么默认120秒,超过300秒将会被设置为300.可是在我的设备上是2400也行。API出错? 
this.startActivity(intentvisible);
获取扫描到的设备 实现步骤: 调用开始扫描的代码 需要权限: 消耗12秒的时间,当扫描到广播后,会发送广播消息,注册一个广播来接收 注册一个扫描完毕的广播,在这个广播中关闭扫描到蓝牙通知的广播,并且关闭自己
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//开始扫描
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter(); 
ba.startDiscovery(); 
//注册这个扫描广播
IntentFilter intentfilter=new IntentFilter(BluetoothDevice.ACTION_FOUND); 
       MyReceiver mr=new MyReceiver(); 
       this.registerReceiver(mr, intentfilter); 
 
//注册一个扫描完毕的广播
class FinishFound extends BroadcastReceiver 
   
   
    @Override 
    public void onReceive(Context context, Intent intent) { 
        BluetoothActivity.this.unregisterReceiver(this); 
        BluetoothActivity.this.unregisterReceiver(mr); 
    
       
   }
获取已经配对的蓝牙设备(集合) 实现步骤: 获取集合。 需要权限:
1
2
3
4
5
6
7
8
Set<bluetoothdevice> device=ba.getBondedDevices(); 
     if(device.size()>0) 
    
       for(BluetoothDevice bd:device) 
        
            System.out.println(bd.getAddress()+bd.getName()); 
        
    }</bluetoothdevice>
蓝牙发送数据(发送字符串) 实现步骤:
发送字符串到一个配对的设备。 需要已知名和地址。
1
2
3
4
5
6
7
8
9
10
11
12
private void sendDataToPairedDevice(String message ,BluetoothDevice device){      
           byte[] toSend = message.getBytes();
            try {
                UUID applicationUUID = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
                BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
                OutputStream mmOutStream = socket.getOutputStream();
                mmOutStream.write(toSend);
                // Your Data is sent to  BT connected paired device ENJOY.
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }
调用以上的方法:
1
sendDataToPairedDevice("text to send" ,bluetoothDevice);
蓝牙接收数据 实现步骤:
启动一个service去监听是否有数据返回。一旦有数据返回就启动一个线程去处理数据 处理完数据,通过广播去通知UI。 服务类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 *负责监听启动应用程序 后的接收数据
 */
public class ReceiveThread extends Service {
  
    private Socket socket;
    private String workStatus;  // 当前工作状况,null表示正在处理 | success表示处理成功,failure表示处理失败
    public static Boolean mainThreadFlag = true//状态
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    private void doListen()
    {
        Log.d("chl", "doListen()");
        //开始监听
        while (mainThreadFlag)
        {
         //开始监听数据
          new Thread(new ThreadReadWriterSocketServer(ReceiveThread.this, socket));
        }
    }
}
线程工作类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ThreadReadWriterSocketServer implements Runnable{
    private  Socket client=null;
    private Context context=null;
    public ThreadReadWriterSocketServer(Context context,Socket client)
    {
        this.context=context;
        this.client=client;
    }
      
      
    @Override
    public void run()
    {
        Receive();
    }
      
      
    private void Receive() {
    //处理数据 
    }
}
十六进制转换 蓝牙通信需要通常转换十六进制进行,方法如下
1
2
3
4
5
6
7
8
9
10
11
public static String bytesToHexString(byte[] bytes) {
       String result = "";
       for (int i = 0; i < bytes.length; i++) {
           String hexString = Integer.toHexString(bytes[i] & 0xFF);
           if (hexString.length() == 1) {
               hexString = '0' + hexString;
           }
           result += hexString.toUpperCase();
       }
       return result;
   }

本文链接:https://it72.com/2431.htm

推荐阅读
最新回复 (2)
  • sendDataToPairedDevice("text to send" ,bluetoothDevice); 这一行的bluetoothDevice我写到android studio里面以后是红色的,请问是什么原因。。
  • BethanySeverance 2015-12-21
    引用 3
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    private void sendDataToPairedDevice(String message ,BluetoothDevice device){      
               byte[] toSend = message.getBytes();
                try {
                    UUID applicationUUID = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
                    OutputStream mmOutStream = socket.getOutputStream();
                    mmOutStream.write(toSend);
                    // Your Data is sent to  BT connected paired device ENJOY.
                } catch (IOException e) {
                    Log.e(TAG, "Exception during write", e);
                }
            }
返回