蓝牙的有关知识
蓝牙
- 蓝牙
- 蓝牙,是一种支持设备短距离通信(一般是10m以内,且没有阻隔媒介)的无线电技术,能在包括移动电话、PDA、无线耳机、笔记本电脑等众多设备之间进行无线信息交互,利用这个技术,能够有效的简化通信终端设备之间的通信,也能够成功的简化设备与Intent之间的通信,这样数据传输变得更加告诉快捷,为无线通信拓宽道路
- 注意:
- Android2.0引入蓝牙接口,在开发时候,需要真机调试,如果需要数据传输,还需要两台机器,另外要支持硬件支持
- 蓝牙设备操作
- 1、权限:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
-
2、打开蓝牙的两种方式:
-
(1)、Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//打开本机的蓝牙发现功能(默认是120s,一个应用程序可以设定的最长时间为3600s)
startActivityForResult(enable,REQUEST_ENABLE); -
(2) BluetoothAdapter buletooth = BluetoothAdapter.getDefaultAdapter();
buletooth.enable();
-
-
3、关闭蓝牙的方式
- BluetoothAdapter buletooth = BluetoothAdapter.getDefaultAdapter(); buletooth.disable();
-
4、扫描蓝牙的方式
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
//返回的是一个可用蓝牙的集合
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice bd:bondedDevices) {
Log.d("MainActivity", bd.getName() + bd.getAddress());
} -
蓝牙通信案例
-
UUID
- 是Universally Unique Identifier 的简称,通用唯一识别码的意思,对于蓝牙设备,每个服务都有通用的、独立、唯一的UUID与之对应,在同一时间、同一地点、不可能有两个相同的UUID标识的不同服务
- 在android手机开发中不可过多的考虑到这一点,因为几乎没有哪个手机会同时装两块芯片
这个是蓝牙通信案例的服务器端:
package com.example.myblutooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.hardware.camera2.params.BlackLevelPattern;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.UUID;
public class ServerSocketActivity extends AppCompatActivity implements View.OnClickListener {
private static final int SET_EDITEXT_NULL = 0x4;
private static final int CONN_SUCCESS = 0x1;
private static final int CONN_FAIL = 0x2;
private static final int RECEIVER_INFO = 0x3;
private TextView servertext;
private EditText ettext;
private Button send;
BluetoothAdapter bluetooth = null; //本地蓝牙设备
BluetoothServerSocket mServerSocket = null; //蓝牙设备Socket服务端
BluetoothSocket mSocket = null; //蓝牙设备Socket客户端
//输入输出流
PrintStream out;
BufferedReader in;
private String mInfo;
private boolean isReceiver = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_socket);
setTitle("蓝牙服务器");
initialize();
init();
}
/**
* 创建蓝牙服务器端socket
*/
private void init() {
servertext.setText("服务器已启动,正在等待连接。。。。\n");
new Thread(new Runnable() {
@Override
public void run() {
//得到本地数据
bluetooth = BluetoothAdapter.getDefaultAdapter();
try {
//地址 唯一的UUID(这个自己定义,但是两个设备要用的一样 8 4 4 12)
mServerSocket = bluetooth.listenUsingRfcommWithServiceRecord("test,", UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
//阻塞等待Socket客户端请求
mSocket = mServerSocket.accept();
if (mSocket != null) {
out = new PrintStream(mSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
}
mHandler.sendEmptyMessage(CONN_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
Message msg = mHandler.obtainMessage(CONN_FAIL, e.getLocalizedMessage());
mHandler.sendMessage(msg);
}
}
}).start();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case RECEIVER_INFO:
setInfo(msg.obj.toString() + "\n");
break;
case SET_EDITEXT_NULL:
ettext.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功\n");
send.setEnabled(true);
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败\n");
setInfo(msg.obj.toString() + "\n");
break;
default:
break;
}
}
};
private void initialize() {
servertext = (TextView) findViewById(R.id.server_text);
ettext = (EditText) findViewById(R.id.et_text);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(this);
}
/**
* 拼接消息
* @param info
*/
public void setInfo(String info) {
mInfo = info;
StringBuffer sb = new StringBuffer();
sb.append(servertext.getText());
sb.append(info);
servertext.setText(sb);
}
@Override
public void onClick(View v) {
final String content = ettext.getText().toString();
if (!TextUtils.isEmpty(content)){
new Thread(new Runnable() {
@Override
public void run() {
out.println(content);
out.flush();
mHandler.sendEmptyMessage(SET_EDITEXT_NULL);
}
}).start();
}
Toast.makeText(this, "不能发送空的消息", Toast.LENGTH_SHORT).show();
}
/**
* 接收消息的线程
*/
private class ReceiverInfoThread implements Runnable {
@Override
public void run() {
String info = null;
while (isReceiver){
try {
info = in.readLine();
Message msg = mHandler.obtainMessage(RECEIVER_INFO,info);
mHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
这个是蓝牙案例的客户端:
package com.example.myblutooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.UUID;
public class SocketBluetoothActivity extends AppCompatActivity {
private static final int SET_EDITEXT_NULL = 0x4;
private static final int CONN_SUCCESS = 0x1;
private static final int CONN_FAIL = 0x2;
private static final int RECEIVER_INFO = 0x3;
BluetoothAdapter bluetooth = null; //本地蓝牙设备
BluetoothServerSocket mServerSocket = null; //蓝牙设备Socket服务端
BluetoothSocket mSocket = null; //蓝牙设备Socket客户端
//输入输出流
PrintStream out;
BufferedReader in;
private TextView servertext;
private EditText ettext;
private Button send;
private BluetoothDevice mDevice;
private boolean isReceiver = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_bluetooth);
setTitle("蓝牙客户端");
initialize();
init();
}
/**
* 初始化socket
*/
private void init() {
servertext.setText("服务器已启动,正在等待连接。。。。\n");
new Thread(new Runnable() {
@Override
public void run() {
//得到本地蓝牙设备的默认适配器
bluetooth = BluetoothAdapter.getDefaultAdapter();
mDevice = bluetooth.getRemoteDevice("74:52:AB:4D:80:77");
//根据UUID 创建并返回一个BluetoothSocket
try {
mSocket = mDevice.createRfcommSocketToServiceRecord(UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
if (mSocket != null){
//连接
mSocket.connect();
//获取输入输出流
out = new PrintStream(mSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
}
mHandler.sendEmptyMessage(CONN_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
Message msg = mHandler.obtainMessage(CONN_FAIL, e.getLocalizedMessage());
mHandler.sendMessage(msg);
}
}
}).start();
}
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case RECEIVER_INFO:
setInfo(msg.obj.toString() + "\n");
break;
case SET_EDITEXT_NULL:
ettext.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功\n");
send.setEnabled(true);
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败\n");
setInfo(msg.obj.toString() + "\n");
break;
default:
break;
}
}
};
/**
* 接收消息的线程
*/
private class ReceiverInfoThread implements Runnable {
@Override
public void run() {
String info = null;
while (isReceiver){
try {
info = in.readLine();
Message msg = mHandler.obtainMessage(RECEIVER_INFO,info);
mHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void initialize() {
servertext = (TextView) findViewById(R.id.server_text);
ettext = (EditText) findViewById(R.id.et_text);
send = (Button) findViewById(R.id.send);
}
/**
* 拼接消息
* @param info
*/
public void setInfo(String info) {
StringBuffer sb = new StringBuffer();
sb.append(servertext.getText());
sb.append(info);
servertext.setText(sb);
}
}
网友评论