最近一直在研究两个手机用过蓝牙通信,参考了部分网上代码,到最后也没弄清楚。(楼主是学渣......)
然后有一个项目要用手机通过蓝牙控制三色灯,我就随意写了一下客户端的应用程序,而且没有测试,通过博客记录一下方便以后使用测试。闲话不多说。开始----
参考部分网上代码:
附上链接:http://blog.csdn.net/liuyu973971883/article/details/52495054
该代码可以使用(亲测),我是得到的APK获取到了我手机原先配对过的蓝牙设备的地址,通过日志打印出来,作为我项目的一个目标设备。大家也可以试一试,其中的逻辑讲的非常清楚。
我讲讲我自己的小测试。
布局文件:
由开启蓝牙,关闭蓝牙,红灯,绿灯,蓝灯,关灯按钮构成。
主活动:
UUID 统一标识码
最主要的还是关于BluetoothSocket和BluetoothServerSocket,大家可以看一下API文档。
一,非涉及蓝牙部分,纯粹的乱写代码
主要思路是:按红灯,红灯按钮背景颜色变红,其他变灰色,其他一样。
二,蓝牙部分,该部分思路也是比较乱
首先我已经获取到目标蓝牙设备的地址,所以我只要连接发送就行,并且只要客户端显示成功发送,那就说明客户端是正确的。只是我发了,服务器端收不到,因为根本没有服务器端接受。
1.添加权限
2.代码中需要检测安装APK的机器是支持蓝牙,若不支持,那...
3.获取本地蓝牙适配器
4.选中发送数据的蓝牙设备
5.获取到客户端接口
6.向服务器端发送连接
7.获取字符输出流
8.发送数据
9.完成
大家可以根据我的代码自己测试一下,然后下一个服务端接收。(我也很是需要)。<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/open_bluetooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="打开蓝牙设备" />
<Button
android:id="@+id/close_bluetooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="关闭蓝牙连接"/>
<Button
android:id="@+id/red"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="红灯" />
<Button
android:id="@+id/green"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="绿灯"/>
<Button
android:id="@+id/blue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="蓝灯"/>
<Button
android:id="@+id/close_all_led"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="关灯"/>
</LinearLayout>
package com.managesoft.nullchen.scm_bluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
/**
* 本地蓝牙请求连接目标ble设备,并向其发送数据包
* 目标设备仅有一盏灯 A B C 不可能同时呈现打开状态
* 当灯开启时 A B C 中仅有一个为真 其余两个为假
* 当灯关闭时 A B C 全为假
* 数据发送
* A 请求开启红灯
* B 请求开启绿灯
* C 请求开启蓝灯
* D 请求关闭灯
*
*/
public class SCM_bluetooth extends AppCompatActivity implements View.OnClickListener{
private final Context TAG = SCM_bluetooth.this;
private final int REQUEST_CODE = 0x001;
private final String bluetoothAddress = "D8:6C:02:A5:83:DD";
//设置连接状态
private int connect_state = 0; //未连接
//设置消息
private int RED = 'A';
private int GREEN = 'B';
private int BLUE = 'C';
private int ALL_CLOSE = 'D';
//定义按钮
private Button close_all_led;
private Button red_button;
private Button green_button;
private Button blue_button;
private Button open_bluetooth;
private Button close_bluetooth;
// 选中发送数据的蓝牙设备,全局变量,否则连接在方法执行完就结束了
private BluetoothDevice selectDevice = null;
// UUID,蓝牙建立链接需要的
private final UUID MY_UUID = UUID
.fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");
private BluetoothSocket clientSocket;
// 获取到向设备写的输出流,全局变量,否则连接在方法执行完就结束了
private OutputStream os;
BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_scm_bluetooth);
//初始化按钮的绑定事件
//获取蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//蓝牙的准备工作 1.检测是否存在本地蓝牙
if(!mBluetoothAdapter.isEnabled()){
return;
}
intitButton();
}
private void intitButton() {
open_bluetooth = (Button)findViewById(R.id.open_bluetooth);
close_bluetooth = (Button)findViewById(R.id.close_bluetooth);
red_button = (Button)findViewById(R.id.red);
green_button = (Button)findViewById(R.id.green);
blue_button = (Button)findViewById(R.id.blue);
close_all_led = (Button)findViewById(R.id.close_all_led);
close_all_led.setOnClickListener(this);
red_button.setOnClickListener(this);
green_button.setOnClickListener(this);
blue_button.setOnClickListener(this);
open_bluetooth.setOnClickListener(this);
close_bluetooth.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.open_bluetooth:
if(mBluetoothAdapter.disable()){
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),REQUEST_CODE);
}else{
ShowToast("蓝牙已开启");
}
break;
case R.id.close_bluetooth:
if(mBluetoothAdapter.enable()){
mBluetoothAdapter.disable();
ShowToast("正在关闭蓝牙...");
ShowToast("蓝牙已关闭");
}else {
ShowToast("蓝牙已关闭");
}
break;
case R.id.red: //点击红色按钮 使得按钮颜色变红 其他色为正常色
red_button.setBackgroundColor(Color.parseColor("#DC143C"));
green_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
blue_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
ShowToast("RED");
Send_Msg_SCM(""+'A');
//此时要求向指定蓝牙设备发送信息 A 使得红灯亮起
break;
case R.id.green:
red_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
green_button.setBackgroundColor(Color.parseColor("#00FF00"));
blue_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
ShowToast("GREEN");
Send_Msg_SCM(""+'B');
//此时要求向指定蓝牙设备发送信息 B 使得红灯亮起
break;
case R.id.blue:
red_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
green_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
blue_button.setBackgroundColor(Color.parseColor("#4169E1"));
ShowToast("BLUE");
Send_Msg_SCM(""+'C');
//此时要求向指定蓝牙设备发送信息 C 使得红灯亮起
break;
case R.id.close_all_led:
red_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
green_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
blue_button.setBackgroundColor(Color.parseColor("#A9A9A9"));
//此时要求向指定蓝牙设备发送信息 D 使得红灯亮起
ShowToast("ALL CLOSE");
Send_Msg_SCM(""+'D');
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(REQUEST_CODE == requestCode){
if(requestCode == RESULT_CANCELED){
ShowToast("蓝牙开启失败");
}else {
ShowToast("蓝牙开启成功");
}
}
}
//发送消息
public void Send_Msg_SCM(String Msg){
if (selectDevice == null) {
//通过地址获取到该设备
selectDevice = mBluetoothAdapter.getRemoteDevice(bluetoothAddress);
}
try {
// 判断客户端接口是否为空
Log.d("selectDevice",selectDevice+"");
if (clientSocket == null) {
// 获取到客户端接口
clientSocket = selectDevice.createRfcommSocketToServiceRecord(MY_UUID);
// 向服务端发送连接
Log.d("clientSocket",clientSocket+"");
clientSocket.connect();
// 获取到输出流,向外写数据
os = clientSocket.getOutputStream();
}
Log.d("os",os+"");
// 判断是否拿到输出流
if (os != null) {
// 需要发送的信息
//String text = "成功发送信息";
// 以utf-8的格式发送出去
String text = Msg;
os.write(text.getBytes("UTF-8"));
ShowToast("发送信息成功");
}
// 吐司一下,告诉用户发送成功
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 如果发生异常则告诉用户发送失败
ShowToast("接收方未打开蓝牙");
}
}
//吐司 打印
public void ShowToast(String string){
Toast toast = Toast.makeText(TAG,string,Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
}