一、功能介绍
可实现两个手机之间的蓝牙通信,通过蓝牙接收和发送消息。
二、步骤及关键代码
1.新建工程MyBluetooth,在AndroidManifest.xml中添加权限申请
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2.修改布局文件activity_main.xml
<?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/btn_openBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/open_bt"/>
<Button
android:layout_marginTop="10dp"
android:id="@+id/btn_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/search"/>
<TextView
android:layout_marginTop="10dp"
android:id="@+id/text_state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/connect_state"/>
<Button
android:layout_marginTop="10dp"
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send_msg"/>
<TextView
android:layout_marginTop="10dp"
android:id="@+id/text_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:layout_marginTop="10dp"
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
3.新建布局文件device_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="58dp"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/device_name"
android:gravity="center_vertical"
android:textColor="#000"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/device_info"
android:gravity="center_vertical|right"
android:textColor="#000"/>
</LinearLayout>
4.修改strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyBluetooth</string>
<string name="open_bt">打开蓝牙</string>
<string name="search">搜索设备</string>
<string name="send_msg">发送消息</string>
<string name="connect_error">连接失败</string>
<string name="connect_success">连接成功</string>
<string name="connecting">连接中</string>
<string name="connect_state">连接状态</string>
<string name="send_msgs">发送数据:</string>
<string name="send_msg_error">发送数据失败:</string>
<string name="get_msg">获取到数据:</string>
</resources>
5.编写MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private BluetoothAdapter bTAdatper;
private ListView listView;
private Device adapter;
private TextView text_state;
private TextView text_msg;
private final int BUFFER_SIZE = 1024;
private static final String NAME = "BT_DEMO";
private static final UUID BT_UUID = UUID.fromString("02001101-0001-1000-8080-00805F9BA9BA");
private ConnectThread connectThread;
private AcceptThread acceptThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
bTAdatper = BluetoothAdapter.getDefaultAdapter();
initReceiver();
acceptThread = new AcceptThread();
acceptThread.start();
}
private void initView() {
findViewById(R.id.btn_openBT).setOnClickListener(this);
findViewById(R.id.btn_search).setOnClickListener(this);
findViewById(R.id.btn_send).setOnClickListener(this);
text_state = (TextView) findViewById(R.id.text_state);
text_msg = (TextView) findViewById(R.id.text_msg);
listView = (ListView) findViewById(R.id.listView);
adapter = new Device(getApplicationContext(), R.layout.device_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (bTAdatper.isDiscovering()) {
bTAdatper.cancelDiscovery();
}
BluetoothDevice device = (BluetoothDevice) adapter.getItem(position);
connectDevice(device);
}
});
}
private void initReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_openBT:
openBlueTooth();
break;
case R.id.btn_search:
searchDevices();
break;
case R.id.btn_send:
if (connectThread != null) {
connectThread.sendMsg("这是蓝牙发送过来的消息");
}
break;
}
}
private void openBlueTooth() {
if (bTAdatper == null) {
Toast.makeText(this, "当前设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
}
if (!bTAdatper.isEnabled()) {
bTAdatper.enable();
}
if (bTAdatper.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(i);
}
}
private void searchDevices() {
if (bTAdatper.isDiscovering()) {
bTAdatper.cancelDiscovery();
}
getBoundedDevices();
bTAdatper.startDiscovery();
}
private void getBoundedDevices() {
Set<BluetoothDevice> pairedDevices = bTAdatper.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
adapter.add(device);
}
}
}
private void connectDevice(BluetoothDevice device) {
text_state.setText(getResources().getString(R.string.connecting));
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BT_UUID);
connectThread = new ConnectThread(socket, true);
connectThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (bTAdatper != null && bTAdatper.isDiscovering()) {
bTAdatper.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
adapter.add(device);
adapter.notifyDataSetChanged();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(MainActivity.this, "开始搜索", Toast.LENGTH_SHORT).show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(MainActivity.this, "搜索完毕", Toast.LENGTH_SHORT).show();
}
}
};
private class ConnectThread extends Thread {
private BluetoothSocket socket;
private boolean activeConnect;
InputStream inputStream;
OutputStream outputStream;
private ConnectThread(BluetoothSocket socket, boolean connect) {
this.socket = socket;
this.activeConnect = connect;
}
@Override
public void run() {
try {
if (activeConnect) {
socket.connect();
}
text_state.post(new Runnable() {
@Override
public void run() {
text_state.setText(getResources().getString(R.string.connect_success));
}
});
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytes;
while (true) {
bytes = inputStream.read(buffer);
if (bytes > 0) {
final byte[] data = new byte[bytes];
System.arraycopy(buffer, 0, data, 0, bytes);
text_msg.post(new Runnable() {
@Override
public void run() {
text_msg.setText(getResources().getString(R.string.get_msg)+new String(data));
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
text_state.post(new Runnable() {
@Override
public void run() {
text_state.setText(getResources().getString(R.string.connect_error));
}
});
}
}
public void sendMsg(final String msg) {
byte[] bytes = msg.getBytes();
if (outputStream != null) {
try {
outputStream.write(bytes);
text_msg.post(new Runnable() {
@Override
public void run() {
text_msg.setText(getResources().getString(R.string.send_msgs)+msg);
}
});
} catch (IOException e) {
e.printStackTrace();
text_msg.post(new Runnable() {
@Override
public void run() {
text_msg.setText(getResources().getString(R.string.send_msg_error)+msg);
}
});
}
}
}
}
private class AcceptThread extends Thread {
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
@Override
public void run() {
try {
serverSocket = bTAdatper.listenUsingRfcommWithServiceRecord(
NAME, BT_UUID);
while (true) {
socket = serverSocket.accept();
text_state.post(new Runnable() {
@Override
public void run() {
text_state.setText(getResources().getString(R.string.connecting));
}
});
connectThread = new ConnectThread(socket, false);
connectThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
6.新建Device.java
package com.example.mybluetooth;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class BlueToothDeviceAdapter extends ArrayAdapter<BluetoothDevice> {
private final LayoutInflater mInflater;
private int mResource;
public BlueToothDeviceAdapter(Context context, int resource) {
super(context, resource);
mInflater = LayoutInflater.from(context);
mResource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(mResource, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.device_name);
TextView info = (TextView) convertView.findViewById(R.id.device_info);
BluetoothDevice device = getItem(position);
name.setText(device.getName());
info.setText(device.getAddress());
return convertView;
}
}
三、运行效果展示
1.界面 2.发送消息 3,。接收消息
四、源代码仓库地址
https://gitee.com/huang-jingwen0328/MyBluetooth
|