蓝牙设备操作
权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
使用
打开蓝牙
public void openBluetoothClick(View view) {
// 打开对话框询问是否开启蓝牙
// Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// enabler.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
// startActivity(enabler);
// 直接打开蓝牙
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable();
}
关闭蓝牙
public void closeBluetoothClick(View view) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.disable();
}
搜索蓝牙设备
public void scanBluetoothClick(View view) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();//开始扫描蓝牙设备
Set<BluetoothDevice> set = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice bd:set){
System.out.println("name:"+bd.getName());
System.out.println("address:"+bd.getAddress());
}
}
蓝牙发送
客户端:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 ClientBluetoothActivity extends AppCompatActivity {
private static final int CONN_SUCCESS = 0x1;
private static final int CONN_FAIL = 0x2;
private static final int RECEIVER_INFO = 0x3;
private static final int SET_EDITTEXT_NULL = 0x4;
private Button button_send;
private TextView textView_content;
private EditText editText_info;
BluetoothAdapter bluetooth = null;//本地蓝牙设备
BluetoothDevice device = null;//远程蓝牙设备
BluetoothSocket socket = null;//蓝牙Socket客户端
//输入输出流
PrintStream out;
BufferedReader in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_bluetooth);
setTitle("蓝牙客户端");
textView_content = (TextView)findViewById(R.id.textView_content);
button_send = (Button) findViewById(R.id.button_send);
editText_info = (EditText) findViewById(R.id.editText_info);
init();
}
private void init() {
textView_content.setText("正在与服务器连接...\n");
new Thread(new Runnable() {
@Override
public void run() {
try {
bluetooth = BluetoothAdapter.getDefaultAdapter();
device = bluetooth.getRemoteDevice("74:51:BA:F2:80:75");
socket = device.createRfcommSocketToServiceRecord(UUID
.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
if (socket!=null){
socket.connect();
out = new PrintStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
handler.sendEmptyMessage(CONN_SUCCESS);
} catch (IOException e) {
e.printStackTrace();
Message msg = handler.obtainMessage(CONN_FAIL,e.getLocalizedMessage());
handler.sendMessage(msg);
}
}
}).start();
}
private boolean isReceiver = true;
class ReceiverInfoThread implements Runnable{
@Override
public void run() {
String info = null;
while (isReceiver){
try {
System.out.println("------------------------------ReceiverInfoThread start....");
info = in.readLine();
System.out.println("------------------------------ReceiverInfoThread read....");
Message msg = handler.obtainMessage(RECEIVER_INFO,info);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private Handler handler = 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_EDITTEXT_NULL:
editText_info.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功\n");
button_send.setEnabled(true);
System.out.println("Name="+device.getName());
System.out.println("getUuids="+device.getUuids());
System.out.println("getAddress="+device.getAddress());
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败\n");
setInfo(msg.obj.toString()+"\n");
break;
default:
break;
}
}
};
public void sendClick(View view) {
final String content = editText_info.getText().toString();
if (TextUtils.isEmpty(content)){
Toast.makeText(this,"不能发送空消息",Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
out.println(content);
out.flush();
handler.sendEmptyMessage(SET_EDITTEXT_NULL);
}
}).start();
}
private void setInfo(String info){
StringBuffer sb = new StringBuffer();
sb.append(textView_content.getText());
sb.append(info);
textView_content.setText(sb);
}
}
服务端:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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 ServerBluetoothActivity extends Activity {
private static final int CONN_SUCCESS = 0x1;
private static final int CONN_FAIL = 0x2;
private static final int RECEIVER_INFO = 0x3;
private static final int SET_EDITTEXT_NULL = 0x4;
private Button button_send;
private TextView textView_content;
private EditText editText_info;
BluetoothAdapter bluetooth = null;//本地蓝牙设备
BluetoothServerSocket serverSocket = null;//蓝牙设备Socket服务端
BluetoothSocket socket = null;//蓝牙设备Socket客户端
//输入输出流
PrintStream out;
BufferedReader in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_bluetooth);
setTitle("蓝牙服务端");
textView_content = (TextView)findViewById(R.id.textView_content);
button_send = (Button) findViewById(R.id.button_send);
editText_info = (EditText) findViewById(R.id.editText_info);
init();
}
private void init() {
textView_content.setText("服务器已启动,正在等待连接...\n");
new Thread(new Runnable() {
@Override
public void run() {
bluetooth = BluetoothAdapter.getDefaultAdapter();
try {
serverSocket = bluetooth.listenUsingRfcommWithServiceRecord("test", UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
socket = serverSocket.accept();
if (socket!=null){
out = new PrintStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
handler.sendEmptyMessage(CONN_SUCCESS);
} catch (IOException e) {
e.printStackTrace();
Message msg = handler.obtainMessage(CONN_FAIL,e.getLocalizedMessage());
handler.sendMessage(msg);
}
}
}).start();
}
private Handler handler = 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_EDITTEXT_NULL:
editText_info.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功\n");
button_send.setEnabled(true);
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败\n");
setInfo(msg.obj.toString()+"\n");
break;
default:
break;
}
}
};
private boolean isReceiver = true;
class ReceiverInfoThread implements Runnable{
@Override
public void run() {
String info = null;
while (isReceiver){
try {
info = in.readLine();
Message msg = handler.obtainMessage(RECEIVER_INFO,info);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendClick(View view) {
final String content = editText_info.getText().toString();
if (TextUtils.isEmpty(content)){
Toast.makeText(this,"不能发送空消息",Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
out.println(content);
out.flush();
handler.sendEmptyMessage(SET_EDITTEXT_NULL);
}
}).start();
}
private void setInfo(String info){
StringBuffer sb = new StringBuffer();
sb.append(textView_content.getText());
sb.append(info);
textView_content.setText(sb);
}
}