AndroidStudio蓝牙通信
文章目录
- 一、功能需求
- 二、页面布局设置
- 1. 中间列表list_item.xml布局
- 2. activity_main.xml
- 三、页面跳转控制(java文件)
- 1. MainActivity.java
- 2. ConnectThread连接线程
- 3. openBluetooth蓝牙开启函数
- 4. BlueToothAdapter.java适配器
- 四、运行界面展示
- 五、源码
一、功能需求
进行蓝牙通信的简要设计与开发
二、页面布局设置
1. 中间列表list_item.xml布局
创建layout文件top.xml中,添加文本框,添加文字,设置为居中,修改文字颜色和LinearLayout背景颜色。
<?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="50dp"android:padding="8dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:id="@+id/blue_name"android:gravity="center_vertical"android:textColor="#000000"/><TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/blue_info"android:gravity="center_vertical|right"android:textColor="#000000"/></LinearLayout>
2. activity_main.xml
我想要的效果是页面最上方开启蓝牙,中间显示可连接设备,最下方用于接收消息和发送消息。可以一排两个内容设置一个LinearLayout,其中分别是bottom和text,用来展示信息。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="@drawable/photo"android:padding="20dp"><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><Buttonandroid:id="@+id/btn_openBT"android:layout_width="wrap_content"android:layout_height="wrap_content"android:backgroundTint="@color/colorPrimaryDark"android:text="设置在线"/><TextViewandroid:id="@+id/text_state2"android:layout_marginLeft="40dp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/black"android:text="蓝牙已经打开"/></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><Buttonandroid:layout_marginTop="10dp"android:id="@+id/btn_search"android:layout_width="wrap_content"android:layout_height="wrap_content"android:backgroundTint="@color/colorPrimaryDark"android:text="我的好友"/><TextViewandroid:layout_marginTop="10dp"android:id="@+id/text_state"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="40dp"android:textColor="@color/black"/></LinearLayout><ListViewandroid:layout_marginTop="10dp"android:id="@+id/listView"android:layout_width="match_parent"android:layout_height="400dp"android:textColor="@color/white"/><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><Buttonandroid:layout_marginTop="10dp"android:id="@+id/btn_receive"android:layout_width="wrap_content"android:layout_height="wrap_content"android:backgroundTint="@color/colorPrimaryDark"android:text="来信"/><TextViewandroid:id="@+id/text_msg"android:layout_marginTop="10dp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:textColor="@color/black"android:textColorHint="@color/white"android:text="请你发送消息"/></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><Buttonandroid:layout_marginTop="10dp"android:id="@+id/btn_send"android:layout_width="wrap_content"android:layout_height="wrap_content"android:backgroundTint="@color/colorPrimaryDark"android:text="发送"/><EditTextandroid:id="@+id/text_Edit"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginLeft="20dp"android:hint="现在发送的信息是我来选择的"android:textColor="@color/black"android:textColorHint="@color/black"android:textSize="14dp" /></LinearLayout></LinearLayout>
三、页面跳转控制(java文件)
1. MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {private BluetoothAdapter bTAdatper;private ListView listView;private BlueToothAdapter adapter;private TextView text_state;private TextView text_msg;private final int BUFFER_SIZE = 1024;private static final String NAME = "BT_DEMO";private ConnectThread connectThread;private ListenerThread listenerThread;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();bTAdatper = BluetoothAdapter.getDefaultAdapter();initReceiver();listenerThread = new ListenerThread();listenerThread.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 BlueToothDeviceAdapter(getApplicationContext(), R.layout.bluetooth_device_list_item);listView.setAdapter(adapter);listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic 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);}@Overridepublic 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;}}@Overrideprotected void onDestroy() {super.onDestroy();if (bTAdatper != null && bTAdatper.isDiscovering()) {bTAdatper.cancelDiscovery();}unregisterReceiver(mReceiver);}private final BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic 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();}}};public void sendMsg(final String msg) {byte[] bytes = msg.getBytes();if (outputStream != null) {try {//发送数据outputStream.write(bytes);text_msg.post(new Runnable() {@Overridepublic void run() {text_msg.setText(getResources().getString(R.string.send_msgs)+msg);}});} catch (IOException e) {e.printStackTrace();text_msg.post(new Runnable() {@Overridepublic void run() {text_msg.setText(getResources().getString(R.string.send_msg_error)+msg);}});}}}}
2. ConnectThread连接线程
连接线程,专门用来对外发出连接对方蓝牙的请求和处理流程。构造函数里通过 BluetoothDevice.createRfcommSocketToServiceRecord() ,从待连接的 device 产生BluetoothSocket. 然后在 run 方法中 connect ,成功后调用BluetoothChatSevice 的connected() 方法。定义 cancel() 在关闭线程时能够关闭相关socket 。
private class ConnectThread extends Thread {private final BluetoothSocket mmSocket;private final BluetoothDevice mmDevice;public ConnectThread(BluetoothDevice device) {mmDevice = device;BluetoothSocket tmp = null;try {tmp = device.createRfcommSocketToServiceRecord(MY_UUID);} catch (IOException e) {e.printStackTrace();}mmSocket = tmp;}@Overridepublic void run() {setName("ConnectThread");mAdapter.cancelDiscovery();try {mmSocket.connect();} catch (IOException e) {connectionFailed();try {mmSocket.close();} catch (IOException e2) {e.printStackTrace();}ChatService.this.start();return;}synchronized (ChatService.this) {mConnectThread = null;}connected(mmSocket, mmDevice);}public void cancel() {try {mmSocket.close();} catch (IOException e) {e.printStackTrace();}}}
3. openBluetooth蓝牙开启函数
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();}
4. BlueToothAdapter.java适配器
public class BlueToothAdapter 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;}@Overridepublic 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;}
}
四、运行界面展示
五、源码
代码仓库:https://github.com/zhouyuqi1014/bluetooth
AndroidStudio蓝牙通信相关推荐
- 实现Android和PC之间的蓝牙通信
这两天想实现PC和安卓手机的通信,限于水平,知道的方法大概有两种:基于数据包的socket和蓝牙.虽然看起来简单,但调也调了两天多.自己测试了下socket,在室内WIFI环境下时延大概是0.1s.而 ...
- android 输出字节数组,Android蓝牙通信字节数组的数据类型转换 求教!
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 单片机和安卓手机进行蓝牙通信,发送电压数据到手机,恰好每次8位数据(1字节)传给上位机.采用以下代码获得16进制字符输出,以下是蓝牙通信接收并显示数据部分 ...
- Android蓝牙通信具体解释
蓝牙通信的大概过程例如以下: 1.首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket.获取输入输出流 4,读取和写入数据 5.断开连接关闭蓝牙 还要发送配对码发送进行推断! 以下是全部的源码:不 ...
- Android -传统蓝牙通信聊天
概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设备.蓝牙连接.通信等. 详细 代码下载:http://www.demodashi.com/demo/10676.html 原文地址: Andr ...
- Qt on Android 蓝牙通信开发
版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...
- python 蓝牙开发_基于python实现蓝牙通信代码实例
这篇文章主要介绍了基于python实现蓝牙通信代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 安装和示例 linux下安装 sudo apt ...
- android 蓝牙通信编程
http://blog.csdn.net/yudajun/article/details/8362916 公司项目涉及蓝牙通信,所以就简单的学了学,下面是自己参考了一些资料后的总结,希望对大家有帮助. ...
- android之普通蓝牙通信
参考: https://www.cnblogs.com/demodashi/p/9436608.html https://www.android-doc.com/guide/topics/connec ...
- Android蓝牙通信
Android蓝牙串口通讯 闲着无聊玩起了Android蓝牙模块与单片机蓝牙模块的通信,简单思路就是要手机通过蓝牙发送控制指令给单片机,并作简单的控制应用.单片机的蓝牙模块连接与程序暂且略过,此文主要 ...
最新文章
- 架构设计-业务逻辑层简述
- C#GDI画圆及填充
- 文件夹恢复后java运行慢,eclipse中每次重新启动服务,运行环境下的文件夹或者文件被还原...
- 不吃不喝,两周业余时间研究(cisco SCE CM )
- GWT HTTP请求替代
- 深入react技术栈(1):React简介
- 【floyd】【bitset】洛谷 P1841 [JSOI2007]重要的城市 题解
- CVPR2021 DRConv:即插即用!旷视孙剑、张祥雨团队提出动态区域感知的卷积,涨点显著!...
- Android—SDCard数据存取Environment简介
- 南洋oj 题目144小珂的苦恼
- 牛客小白月赛2 I.艺
- 计算机硬盘中有许多碎片,电脑磁盘碎片整理有什么用(需要经常清理吗)
- 四层交换机实现负载均衡
- 苹果手机屏幕上有白点怎么办
- 诡异的The inferior stopped because it triggered an exception错误
- workflow工作流类型及其区别
- SQL语句和sql函数
- 如何把两张图片拼在一起?
- office移动端_告别微软全家桶,手机版「三合一」的 Office 终于来了
- [译]声明式编程:它是一个真实的东西?