啦啦毕业了,毕业前要写毕业设计,需要写一个简单的蓝牙APP进行交互,通过参考网上资料,问题顺利搞定,下面小编把具体实现思路分享给大家,供大家参考。
1、AndroID蓝牙编程
蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码(Universally Unique IDentifIEr),这是一个软件构建的标准,也是被开源基金会组织应用在分布式计算环境领域的一部分。在蓝牙3.0及下一版本中,UUID被用于唯一标识一个服务,比如文件传输服务,串口服务、打印机服务等,如下:
#蓝牙串口服务 SerialPortServiceClass_UUID = '{00001101-0000-1000-8000-00805F9B34FB}' LANAccessUsingPPPServiceClass_UUID = '{00001102-0000-1000-8000-00805F9B34FB}'#拨号网络服务 DialupNetworkingServiceClass_UUID = '{00001103-0000-1000-8000-00805F9B34FB}'#信息同步服务 IrMCSyncServiceClass_UUID = '{00001104-0000-1000-8000-00805F9B34FB}' SDP_OBEXObjectPushServiceClass_UUID = '{00001105-0000-1000-8000-00805F9B34FB}'#文件传输服务 OBEXfileTransferServiceClass_UUID = '{00001106-0000-1000-8000-00805F9B34FB}' IrMCSyncCommandServiceClass_UUID = '{00001107-0000-1000-8000-00805F9B34FB}'
蓝牙的连接有主从设备,提供服务的可以认为是从设备。主设备通过UUID访问从设备提供具有相同UUID的服务,从而建立客服端―服务器(C/S)模式。
2、编程步骤
AndroID使用蓝牙,需要获得权限,蓝牙权限获得代码如下:
<!-- 蓝牙权限 --><uses-permission androID:name="androID.permission.BLUetoOTH"/><uses-permission androID:name="androID.permission.BLUetoOTH_admin"/>
获取本地蓝牙适配器,如果蓝牙未开启,开启蓝牙设备:
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (bluetoothAdapter == null) {// Device does not support Bluetoothreturn;}// 开启蓝牙int REQUEST_ENABLE_BT = 1;if (!bluetoothAdapter.isEnabled()) {Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(intent,REQUEST_ENABLE_BT);}
搜索已配对的蓝牙设备,并添加到已配对列表中:
// 查询配对设备List<String> devices = new ArrayList<String>();Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();for (BluetoothDevice device : bondedDevices) {devices.add(device.getname() + "-" + device.getAddress());}
搜索未配对蓝牙设备,并添加到未配对列表:
mBluetoothAdapter.startdiscovery();//开始收索 搜索接收函数: final broadcastReceiver mReceiver = new broadcastReceiver() {public voID onReceive(Context context,Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) {// Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Add the name and address to an array adapter to show in a ListVIEw mArrayAdapter.add(device.getname() + "\n" + device.getAddress()); }}};// 收索接收函数需要注册: // Register the broadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver,filter); // Don't forget to unregister during onDestroy
如果是服务器端,需要建立监听,注意监听的是某个服务的UUID,服务器监听类如下:
private class ConnectThread extends Thread {private final String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";private final BluetoothSocket socket;private final BluetoothDevice device;public ConnectThread(BluetoothDevice device) {this.device = device;BluetoothSocket tmp = null;try {tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));} catch (IOException e) {e.printstacktrace();}this.socket = tmp;}public voID run() {bluetoothAdapter.canceldiscovery();try {socket.connect();connectedThread = new ConnectedThread(socket);connectedThread.start();} catch (IOException e) {try {socket.close();} catch (IOException ee) {ee.printstacktrace();}return;}//manageConnectedSocket(socket);}public voID cancel() {try {socket.close();} catch (IOException e) {e.printstacktrace();}}}
客户端与服务器端建立连接成功后,需要ConnectedThread类接收发送数据:
// 客户端与服务器建立连接成功后,用ConnectedThread收发数据private class ConnectedThread extends Thread {private final BluetoothSocket socket;private final inputStream inputStream;private final OutputStream outputStream;public ConnectedThread(BluetoothSocket socket) {this.socket = socket;inputStream input = null;OutputStream output = null;try {input = socket.getinputStream();output = socket.getoutputStream();} catch (IOException e) {e.printstacktrace();}this.inputStream = input;this.outputStream = output;}public voID run() {byte[] buff = new byte[1024];int bytes;while (true) {try {bytes = inputStream.read(buff);String str = new String(buff,"ISO-8859-1");str = str.substring(0,bytes);Log.e("recv",str);} catch (IOException e) {e.printstacktrace();break;}}}public voID write(byte[] bytes) {try {outputStream.write(bytes);} catch (IOException e) {e.printstacktrace();}}public voID cancel() {try {socket.close();} catch (IOException e) {e.printstacktrace();}}}
到此为止就是蓝牙开发的大致步骤,其中没有涉及到蓝牙客户端建立连接类,不过可查阅BLE和经典蓝牙AndroID开发。
3、毕设蓝牙APP介绍
毕设蓝牙APP需要接收单片机通过蓝牙模块发送上来的数据,并且蓝牙APP也可以给单片机发送数据来进行控制。页面布局如下,一个是整体页面,一个是设置页面,测试手机是魅蓝note。因为毕设做的是十字路口红绿灯控制系统,所有页面布局有4个LED灯,分别代表路口的4个红绿灯,会根据时间不同显示不同的颜色(红/绿/黄),并且会显示倒计时,最后来一张红绿灯系统整体图。
activity_main.xml文件如下:
<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent"androID:layout_height="wrap_content" androID:paddingleft="@dimen/activity_horizontal_margin"androID:paddingRight="@dimen/activity_horizontal_margin"androID:paddingtop="@dimen/activity_vertical_margin"androID:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"><linearLayoutandroID:ID="@+ID/linear_layout_top"androID:layout_alignParenttop="true"androID:layout_wIDth="match_parent"androID:layout_height="40dp"><TextVIEwandroID:ID="@+ID/notice_vIEw"androID:layout_wIDth="0dp"androID:layout_height="40dp"androID:text="蓝牙未开启"androID:layout_weight="3"/><TextVIEwandroID:ID="@+ID/notice_recv_vIEw"androID:layout_wIDth="0dp"androID:layout_height="30dp"androID:layout_weight="3"/><TextVIEwandroID:ID="@+ID/notice_send_vIEw"androID:layout_wIDth="0dp"androID:layout_height="30dp"androID:layout_weight="3"/><buttonandroID:ID="@+ID/turn_on_off"androID:layout_wIDth="0dp"androID:layout_height="40dp"androID:layout_weight="2"androID:text="ON"/></linearLayout><TextVIEwandroID:ID="@+ID/led1"androID:layout_centerHorizontal="true"androID:layout_below="@+ID/linear_layout_top"androID:layout_wIDth="40dp"androID:layout_height="20dp"androID:gravity="center"androID:text="LED1"/><TextVIEwandroID:ID="@+ID/led0"androID:layout_centerHorizontal="true"androID:layout_below="@+ID/led1"androID:layout_wIDth="40dp"androID:layout_height="20dp"androID:gravity="center"androID:text="+"/><TextVIEwandroID:ID="@+ID/led3"androID:layout_below="@+ID/led1"androID:layout_toleftOf="@+ID/led1"androID:layout_wIDth="40dp"androID:layout_height="20dp"androID:gravity="center"androID:text="LED3"/><TextVIEwandroID:ID="@+ID/led2"androID:layout_centerHorizontal="true"androID:layout_below="@+ID/led3"androID:layout_wIDth="40dp"androID:layout_height="20dp"androID:gravity="center"androID:text="LED2"/><TextVIEwandroID:ID="@+ID/led4"androID:layout_below="@+ID/led1"androID:layout_toRightOf="@+ID/led1"androID:layout_wIDth="40dp"androID:layout_height="20dp"androID:gravity="center"androID:text="LED4"/><ScrollVIEwandroID:ID="@+ID/scroll_vIEw"androID:layout_below="@+ID/led2"androID:layout_above="@+ID/linear_layout_bottom"androID:layout_wIDth="match_parent"androID:layout_height="match_parent"><TextVIEwandroID:ID="@+ID/recv_vIEw"androID:text=""androID:layout_wIDth="wrap_content"androID:layout_height="wrap_content" /></ScrollVIEw><linearLayoutandroID:ID="@+ID/linear_layout_bottom"androID:layout_alignParentBottom="true"androID:layout_wIDth="match_parent"androID:layout_height="50dp"><buttonandroID:ID="@+ID/clear_recv_vIEw"androID:layout_wIDth="0dp"androID:layout_height="match_parent"androID:layout_weight="1"androID:text="clear" /><EditTextandroID:ID="@+ID/send_text"androID:layout_wIDth="0dp"androID:layout_height="wrap_content"androID:layout_weight="3"androID:hint="输入框,默认@#结尾"/><buttonandroID:ID="@+ID/send"androID:layout_wIDth="0dp"androID:layout_height="match_parent"androID:layout_weight="1"androID:text="send" /></linearLayout></relativeLayout>
MainActivity.java文件如下:
package com.luoxn28.bluetooth;import androID.bluetooth.BluetoothAdapter;import androID.bluetooth.BluetoothDevice;import androID.bluetooth.BluetoothSocket;import androID.content.Intent;import androID.graphics.color;import androID.os.Bundle;import androID.os.Message;import androID.support.v7.app.ActionBaractivity;import androID.vIEw.Menu;import androID.vIEw.MenuItem;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.EditText;import androID.Widget.ScrollVIEw;import androID.Widget.TextVIEw;import androID.Widget.Toast;import java.io.IOException;import java.io.inputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.UUID;public class MainActivity extends ActionBaractivity implements VIEw.OnClickListener {public static final int RECV_VIEW = 0;public static final int NOTICE_VIEW = 1;private BluetoothAdapter bluetoothAdapter = null;private ConnectThread connectThread = null;private ConnectedThread connectedThread = null;private TextVIEw noticeVIEw = null;private button turnOnOff = null;private TextVIEw led0,led1,led2,led3,led4;ScrollVIEw scrollVIEw = null;private TextVIEw recvVIEw = null;private button clearRecvVIEw = null;private EditText sendText = null;private button send = null;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentVIEw(R.layout.activity_main);// 获取BluetoothAdapterbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (bluetoothAdapter == null) {// Device does not support Bluetoothreturn;}// 注册监听事件noticeVIEw = (TextVIEw) findVIEwByID(R.ID.notice_vIEw);turnOnOff = (button) findVIEwByID(R.ID.turn_on_off);led0 = (TextVIEw) findVIEwByID(R.ID.led0);led1 = (TextVIEw) findVIEwByID(R.ID.led1);led2 = (TextVIEw) findVIEwByID(R.ID.led2);led3 = (TextVIEw) findVIEwByID(R.ID.led3);led4 = (TextVIEw) findVIEwByID(R.ID.led4);scrollVIEw = (ScrollVIEw) findVIEwByID(R.ID.scroll_vIEw);recvVIEw = (TextVIEw) findVIEwByID(R.ID.recv_vIEw);clearRecvVIEw = (button) findVIEwByID(R.ID.clear_recv_vIEw);sendText = (EditText) findVIEwByID(R.ID.send_text);send = (button) findVIEwByID(R.ID.send);turnOnOff.setonClickListener(this);clearRecvVIEw.setonClickListener(this);send.setonClickListener(this);if (!bluetoothAdapter.isEnabled()) {noticeVIEw.setText("蓝牙未开启");}else {noticeVIEw.setText("蓝牙已开启");}noticeVIEw.setBackgroundcolor(color.GRAY);led0.setBackgroundcolor(color.GRAY);led1.setBackgroundcolor(color.GRAY);led2.setBackgroundcolor(color.GRAY);led3.setBackgroundcolor(color.GRAY);led4.setBackgroundcolor(color.GRAY);}private boolean isOn = false;@OverrIDepublic voID onClick(VIEw vIEw) {switch (vIEw.getID()) {case R.ID.turn_on_off: // 发送'0'或者'1'都可以if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {Toast.makeText(this,"蓝牙未开启",Toast.LENGTH_SHORT).show();break;}if (connectedThread == null) {Toast.makeText(this,"未连接设备",Toast.LENGTH_SHORT).show();break;}String turn_string = "1@#";connectedThread.write(turn_string.getBytes());if (isOn == false) {isOn = true; // 打开了turnOnOff.setText("OFF");led1.setText("");led2.setText("");led3.setText("");led4.setText("");}else {isOn = false; // 关闭了turnOnOff.setText("ON");led1.setText("LED1");led2.setText("LED2");led3.setText("LED3");led4.setText("LED4");}break;case R.ID.clear_recv_vIEw: // 清空接收框recvVIEw.setText("");break;case R.ID.send: // 发送数据,默认以"@#"结尾if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {Toast.makeText(this,Toast.LENGTH_SHORT).show();return;}if (connectedThread == null) {Toast.makeText(this,Toast.LENGTH_SHORT).show();break;}String inputText = sendText.getText().toString() + "@#"; // 发送给单片机数据以"@#结尾",这样单片机知道一条数据发送结束//Toast.makeText(MainActivity.this,inputText,Toast.LENGTH_SHORT).show();connectedThread.write(inputText.getBytes());break;default:break;}}private androID.os.Handler handler = new androID.os.Handler() {public voID handleMessage(Message msg) {Bundle bundle = null;switch (msg.what) {case RECV_VIEW:if (isOn == false) {isOn = true;turnOnOff.setText("OFF");}bundle = msg.getData();String recv = bundle.getString("recv");recvVIEw.append(recv + "\n");scrollVIEw.fullScroll(ScrollVIEw.FOCUS_DOWN); // 滚动到底部if (recv.isEmpty() || recv.contains(" ") || recv.contains("#")) {break;}int num = Integer.valueOf(recv) / 2; // 0-60sif (num <= 20) {led1.setText("");led2.setText("");led3.setText("");led4.setText("");led1.setBackgroundcolor(color.RED);led2.setBackgroundcolor(color.RED);led3.setBackgroundcolor(color.GREEN);led4.setBackgroundcolor(color.GREEN);}else if (num < 30) {int n = 30 - num;led1.setText("" + n);led2.setText("" + n);if (num < 28) {led3.setBackgroundcolor(color.GREEN);led4.setBackgroundcolor(color.GREEN);}else {led3.setBackgroundcolor(color.YELLOW);led4.setBackgroundcolor(color.YELLOW);}}else if (num <= 50) {led1.setText("");led2.setText("");led3.setText("");led4.setText("");led1.setBackgroundcolor(color.GREEN);led2.setBackgroundcolor(color.GREEN);led3.setBackgroundcolor(color.RED);led4.setBackgroundcolor(color.RED);}else {int n = 60 - num;led3.setText("" + n);led4.setText("" + n);if (num < 58) {led1.setBackgroundcolor(color.GREEN);led2.setBackgroundcolor(color.GREEN);}else {led1.setBackgroundcolor(color.YELLOW);led2.setBackgroundcolor(color.YELLOW);}}break;case NOTICE_VIEW:bundle = msg.getData();String notice = bundle.getString("notice");noticeVIEw.setText(notice);break;default:break;}}};@OverrIDepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main,menu);return true;}@OverrIDepublic boolean onoptionsItemSelected(MenuItem item) {int ID = item.getItemID();if (ID == R.ID.start_bluetooth) {if (bluetoothAdapter != null) {// 开启蓝牙int REQUEST_ENABLE_BT = 1;if (!bluetoothAdapter.isEnabled()) {Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(intent,REQUEST_ENABLE_BT);noticeVIEw.setText("开启蓝牙成功");//Toast.makeText(this,"开启蓝牙成功",Toast.LENGTH_SHORT).show();} else {Toast.makeText(this,"蓝牙已开启",Toast.LENGTH_SHORT).show();}}return true;}else if (ID == R.ID.show_devices) {if (bluetoothAdapter != null) {if (!bluetoothAdapter.isEnabled()) {Toast.makeText(this,Toast.LENGTH_SHORT).show();return true;}// 查询配对设备List<String> devices = new ArrayList<String>();Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();for (BluetoothDevice device : bondedDevices) {devices.add(device.getname() + "-" + device.getAddress());}StringBuilder text = new StringBuilder();for (String device : devices) {text.append(device + "\n");}Toast.makeText(this,text,Toast.LENGTH_SHORT).show();}return true;}else if (ID == R.ID.find_devices) {Toast.makeText(this,"该功能暂时不可用",Toast.LENGTH_SHORT).show();}else if (ID == R.ID.connect_devices) {if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {Toast.makeText(this,Toast.LENGTH_SHORT).show();return true;}// 查询配对设备 建立连接,只能连接第一个配对的设备List<String> devices = new ArrayList<String>();Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();for (BluetoothDevice device : bondedDevices) {connectThread = new ConnectThread(device);connectThread.start();//Toast.makeText(this,"连接成功",Toast.LENGTH_SHORT).show();break;}}return super.onoptionsItemSelected(item);}private class ConnectThread extends Thread {private final String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";private final BluetoothSocket socket;private final BluetoothDevice device;public ConnectThread(BluetoothDevice device) {this.device = device;BluetoothSocket tmp = null;try {tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));} catch (IOException e) {e.printstacktrace();}this.socket = tmp;}public voID run() {bluetoothAdapter.canceldiscovery();try {socket.connect();connectedThread = new ConnectedThread(socket);connectedThread.start();} catch (IOException e) {try {socket.close();} catch (IOException ee) {ee.printstacktrace();}return;}//manageConnectedSocket(socket);}public voID cancel() {try {socket.close();} catch (IOException e) {e.printstacktrace();}}}// 客户端与服务器建立连接成功后,用ConnectedThread收发数据private class ConnectedThread extends Thread {private final BluetoothSocket socket;private final inputStream inputStream;private final OutputStream outputStream;public ConnectedThread(BluetoothSocket socket) {this.socket = socket;inputStream input = null;OutputStream output = null;try {input = socket.getinputStream();output = socket.getoutputStream();} catch (IOException e) {e.printstacktrace();}this.inputStream = input;this.outputStream = output;}public voID run() {StringBuilder recvText = new StringBuilder();byte[] buff = new byte[1024];int bytes;Bundle tmpBundle = new Bundle();Message tmpMessage = new Message();tmpBundle.putString("notice","连接成功");tmpMessage.what = NOTICE_VIEW;tmpMessage.setData(tmpBundle);handler.sendMessage(tmpMessage);while (true) {try {bytes = inputStream.read(buff);String str = new String(buff,bytes);// 收到数据,单片机发送上来的数据以"#"结束,这样手机知道一条数据发送结束//Log.e("read",str);if (!str.endsWith("#")) {recvText.append(str);continue;}recvText.append(str.substring(0,str.length() - 1)); // 去除'#'Bundle bundle = new Bundle();Message message = new Message();bundle.putString("recv",recvText.toString());message.what = RECV_VIEW;message.setData(bundle);handler.sendMessage(message);recvText.replace(0,recvText.length(),"");} catch (IOException e) {e.printstacktrace();break;}}}public voID write(byte[] bytes) {try {outputStream.write(bytes);} catch (IOException e) {e.printstacktrace();}}public voID cancel() {try {socket.close();} catch (IOException e) {e.printstacktrace();}}}}
menu_main.xml文件如下:
<menu xmlns:androID="http://schemas.androID.com/apk/res/androID"xmlns:app="http://schemas.androID.com/apk/res-auto"xmlns:tools="http://schemas.androID.com/tools" tools:context=".MainActivity"><itemandroID:ID="@+ID/show_devices"androID:title="@string/show_devices"androID:orderIncategory="100"app:showAsAction="never" /><itemandroID:ID="@+ID/start_bluetooth"androID:title="@string/start_bluetooth"androID:orderIncategory="100"app:showAsAction="never" /><itemandroID:ID="@+ID/find_devices"androID:title="@string/find_devices"androID:orderIncategory="100"app:showAsAction="never" /><itemandroID:ID="@+ID/connect_devices"androID:title="@string/connect_devices"androID:orderIncategory="100"app:showAsAction="never" /></menu>
strings.xml文件如下:
<resources><string name="app_name">Bluetooth</string><string name="action_settings">Settings</string><string name="start_bluetooth">开启蓝牙</string><string name="show_devices">查询配对设备</string><string name="find_devices">搜索设备</string><string name="connect_devices">连接设备</string></resources>
到这里整个APP已经开发完成,亲测可用,如果有什么错误,欢迎评论指正谈论^_^。
到此,本文全部内容就给大家介绍完了,亲自测试过,代码安全可靠,放心实用,如果有任何问题欢迎给我留言,小编会及时回复的!
总结以上是内存溢出为你收集整理的Android单片机与蓝牙模块通信实例代码全部内容,希望文章能够帮你解决Android单片机与蓝牙模块通信实例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)