1.加入权限

  1. <uses-feature
  2. android:name="android.hardware.bluetooth_le"
  3. android:required="true" />
  4.  
  5. <uses-permission android:name="android.permission.BLUETOOTH" />
  6. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2.代码:

  1. package myapplication.com.myapplicationble;
  2.  
  3. import android.app.Service;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothServerSocket;
  7. import android.bluetooth.BluetoothSocket;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.os.AsyncTask;
  11. import android.os.Handler;
  12. import android.os.IBinder;
  13. import android.os.Message;
  14. import android.support.v7.app.AppCompatActivity;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.widget.Button;
  19. import android.widget.EditText;
  20. import android.widget.PopupMenu;
  21. import android.widget.PopupWindow;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24.  
  25. import java.io.ByteArrayOutputStream;
  26. import java.io.IOException;
  27. import java.io.InputStream;
  28. import java.io.OutputStream;
  29. import java.net.Socket;
  30. import java.util.UUID;
  31. public class MainActivity extends AppCompatActivity {
  32.  
  33. private BluetoothAdapter BA;
  34. BluetoothServerSocket mmServerSocket;
  35.  
  36. private static String address = "20:16:09:26:81:80"; // <==应填写蓝牙串口模块的蓝牙地址。
  37. private BluetoothSocket btSocket = null;
  38. private OutputStream outStream = null;
  39. public InputStream inStream = null;
  40. EditText editText;
  41. TextView textView;
  42. Button button, button1;
  43. private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  44.  
  45. @Override
  46. protected void onCreate(Bundle savedInstanceState) {
  47. super.onCreate(savedInstanceState);
  48. setContentView(R.layout.activity_main);
  49.  
  50. initView();
  51.  
  52. }
  53. /**
  54. * 连接蓝牙
  55. * **/
  56. public void connect() {
  57. BA = BluetoothAdapter.getDefaultAdapter();
  58. BluetoothDevice device = BA.getRemoteDevice(address);
  59.  
  60. // pairedDevices = BA.getBondedDevices();
  61. try {
  62. btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  63. // new ReceiveDatas(btSocket).start();
  64. } catch (IOException e) {
  65. }
  66. BA.cancelDiscovery();
  67. try {
  68. btSocket.connect();
  69. // String s="sm";
  70. outStream = btSocket.getOutputStream();
  71. // outStream.write(s.getBytes());
  72. //outStream.write(0x41);
  73.  
  74. inStream = btSocket.getInputStream();
  75. while (true){
  76. byte[] buffer = new byte[100];
  77. int count = inStream.read(buffer);
  78. int a= inStream.available();
  79. String ss= new String(buffer, 0, count, "utf-8");
  80. System.out.println("***A"+ss);
          // 输出信息缺少……不全,占时不会
  81. }
  82.  
  83. } catch (IOException e) {
  84. }
  85. try {
  86. // btSocket.close();
  87. } catch (Exception e2) {
  88.  
  89. // Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
  90. }
  91. }
  92.  
  93. public void initView() {
  94.  
  95. editText = (EditText) findViewById(R.id.edit);
  96. textView = (TextView) findViewById(R.id.textView);
  97. button = (Button) findViewById(R.id.button);
  98. button1 = (Button) findViewById(R.id.button1);
  99. BA = BluetoothAdapter.getDefaultAdapter();
  100. /**
  101. * 连接蓝牙
  102. * */
  103. button1.setOnClickListener(new View.OnClickListener() {
  104. @Override
  105. public void onClick(View v) {
  106. System.out.println("***11");
  107. as();
  108. }
  109. });
  110. /**
  111. * 发送信息
  112. * **/
  113. button.setOnClickListener(new View.OnClickListener() {
  114. @Override
  115. public void onClick(View v) {
  116. String s = editText.getText().toString();
  117. try {
  118.  
  119.           // outStream.write(s.getBytes()); 发送数据
  120.  
  121. outStream = btSocket.getOutputStream();
  122. inStream=btSocket.getInputStream();
  123. outStream.write("sm".getBytes());
  124. outStream.write("\r\n".getBytes());
  125.  
  126. } catch (IOException e) {
  127. e.printStackTrace();
  128. }
  129. }
  130. });
  131.  
  132. }
  133.  
  134. /**
  135. *
  136. * 连接蓝牙
  137. * **/
  138. public void as() {
  139. new AsyncTask() {
  140.  
  141. @Override
  142. protected String doInBackground(Object[] params) {
  143.  
  144. connect();
  145. return null;
  146. }
  147.  
  148. @Override
  149. protected void onPreExecute() {
  150. super.onPreExecute();
  151. }
  152.  
  153. @Override
  154. protected void onPostExecute(Object o) {
  155. super.onPostExecute(o);
  156. Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
  157. }
  158. }.execute();
  159. }
  160.  
  161. }

3.操作图

<1>连接后发送数据oooo到蓝牙,接收端显示oooo

<2> 终端发送数据,手机端打印出数据ooooui  [oooo]是打印的字符串,ui为接收的数据

修改——-->:

接受数据:

  1. private class ConnectedThread extends Thread {
  2. private final BluetoothSocket socket;
  3. private final InputStream inputStream;
  4. private final OutputStream outputStream;
  5. public ConnectedThread(BluetoothSocket socket) {
  6. this.socket = socket;
  7. InputStream input = null;
  8. OutputStream output = null;
  9. try {
  10. input = socket.getInputStream();
  11. output = socket.getOutputStream();
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. this.inputStream = input;
  16. this.outputStream = output;
  17. }
  18. public void run() {
  19. byte[] buff = new byte[1024];
  20. int bytes;
  21. while (true) {
  22. try {
  23. bytes = inputStream.read(buff);
  24. String str = new String(buff, "ISO-8859-1");
  25. str = str.substring(0, bytes);
  26. Log.e("recv", str);
  27.  
  28. Message message=handler.obtainMessage();
  29. message.obj=str;
  30. handler.sendMessage(message);
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. break;
  34. }
  35. }
  36. }
  37. public void write(byte[] bytes) {
  38. try {
  39. outputStream.write(bytes);
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. public void cancel() {
  45. try {
  46. socket.close();
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }

---------------------------------------------------------------------------------------------------------------------------------------------------------

完成后代码:

1.权限:

  1. <uses-feature
  2. android:name="android.hardware.bluetooth_le"
  3. android:required="true" />
  4.  
  5. <uses-permission android:name="android.permission.BLUETOOTH" />
  6. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2.Activity:

  1. package myapplication.com.myapplicationble;
  2.  
  3. import android.app.Service;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothServerSocket;
  7. import android.bluetooth.BluetoothSocket;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.os.AsyncTask;
  11. import android.os.Handler;
  12. import android.os.IBinder;
  13. import android.os.Message;
  14. import android.support.v7.app.AppCompatActivity;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.widget.Button;
  19. import android.widget.EditText;
  20. import android.widget.PopupMenu;
  21. import android.widget.PopupWindow;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24.  
  25. import java.io.BufferedReader;
  26. import java.io.ByteArrayOutputStream;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.InputStreamReader;
  30. import java.io.OutputStream;
  31. import java.net.Socket;
  32. import java.util.ArrayList;
  33. import java.util.UUID;
  34. public class MainActivity extends AppCompatActivity {
  35.  
  36. private BluetoothAdapter BA;
  37. BluetoothServerSocket mmServerSocket;
  38. String message="";
  39. private static String address = "20:16:09:26:81:80"; // <==应填写蓝牙串口模块的蓝牙地址。
  40. private BluetoothSocket btSocket = null;
  41. private OutputStream outStream = null;
  42. public InputStream inStream = null;
  43. EditText editText;
  44. TextView textView;
  45. Button button, button1;
  46. boolean BluetoothFlag;
  47. private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  48.  
  49. @Override
  50. protected void onCreate(Bundle savedInstanceState) {
  51. super.onCreate(savedInstanceState);
  52. setContentView(R.layout.activity_main);
  53.  
  54. initView();
  55.  
  56. }
  57.  
  58. /**
  59. * 连接蓝牙
  60. **/
  61. public void connect() {
  62. BA = BluetoothAdapter.getDefaultAdapter();
  63. BluetoothDevice device = BA.getRemoteDevice(address);
  64.  
  65. // pairedDevices = BA.getBondedDevices();
  66. try {
  67. btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  68. } catch (IOException e) {
  69. }
  70. BA.cancelDiscovery();
  71. try {
  72. btSocket.connect();
  73. // String s="sm";
  74. outStream = btSocket.getOutputStream();
  75. //outStream.write(s.getBytes());
  76. //outStream.write(0x41);
  77. inStream = btSocket.getInputStream();
  78. // while (true){
  79. // byte[] buffer = new byte[1];
  80. // int length = 0;
  81. // byte bb = 0;
  82. // String line = null;
  83. // ArrayList<Byte> list = new ArrayList<Byte>();
  84. // while (inStream.read(buffer) == -1) {
  85. // try {
  86. // Thread.sleep(100);
  87. // } catch (InterruptedException e) {
  88. // e.printStackTrace();
  89. // }
  90. // System.out.print("-->" +inStream.read(buffer));
  91. // }
  92. // }
  93.  
  94. /***
  95. * 1
  96. * **/
  97. // while (true) {
  98. //
  99. // if(inStream.available()>=0){
  100. // byte[] buffer = new byte[1024];
  101. // int count = inStream.read(buffer);
  102. // // System.out.println("***MAX:" + a);
  103. // String ss = new String(buffer, 0, count, "utf-8");
  104. // System.out.println("*--" + ss);
  105. // }
  106. //
  107. // }
  108.  
  109. /****
  110. * 2
  111. * */
  112.  
  113. // BluetoothFlag = true;
  114. // MyThread bluetoothThread = new MyThread();
  115. // bluetoothThread.start();
  116.  
  117. /***
  118. *
  119. * 3
  120. * */
  121.  
  122. ConnectedThread connectedThread = new ConnectedThread(btSocket);
  123. connectedThread.start();
  124.  
  125. } catch (IOException e) {
  126. }
  127. try {
  128. // btSocket.close();
  129. } catch (Exception e2) {
  130.  
  131. // Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
  132. }
  133. }
  134.  
  135. public void initView() {
  136.  
  137. editText = (EditText) findViewById(R.id.edit);
  138. textView = (TextView) findViewById(R.id.textView);
  139. button = (Button) findViewById(R.id.button);
  140. button1 = (Button) findViewById(R.id.button1);
  141. BA = BluetoothAdapter.getDefaultAdapter();
  142. /**
  143. * 连接蓝牙
  144. * */
  145. button1.setOnClickListener(new View.OnClickListener() {
  146. @Override
  147. public void onClick(View v) {
  148. System.out.println("***11");
  149. as();
  150. }
  151. });
  152. /**
  153. * 发送信息
  154. * **/
  155. button.setOnClickListener(new View.OnClickListener() {
  156. @Override
  157. public void onClick(View v) {
  158. String s = editText.getText().toString();
  159. try {
  160.  
  161. outStream = btSocket.getOutputStream();
  162. inStream = btSocket.getInputStream();
  163. // outStream.write("\r\n".getBytes());
  164. outStream.write("sm".getBytes());
  165. outStream.write("\r\n".getBytes());
  166.  
  167. } catch (IOException e) {
  168. e.printStackTrace();
  169. }
  170. }
  171. });
  172.  
  173. }
  174.  
  175. /**
  176. * 连接蓝牙
  177. **/
  178. public void as() {
  179. new AsyncTask() {
  180.  
  181. @Override
  182. protected String doInBackground(Object[] params) {
  183.  
  184. connect();
  185. return null;
  186. }
  187.  
  188. @Override
  189. protected void onPreExecute() {
  190. super.onPreExecute();
  191. }
  192.  
  193. @Override
  194. protected void onPostExecute(Object o) {
  195. super.onPostExecute(o);
  196. Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
  197. }
  198. }.execute();
  199. }
  200.  
  201. /**
  202. * 在接受不到数据
  203. * **/
  204.  
  205. private class ConnectedThread extends Thread {
  206. private final BluetoothSocket socket;
  207. private final InputStream inputStream;
  208. private final OutputStream outputStream;
  209. public ConnectedThread(BluetoothSocket socket) {
  210. this.socket = socket;
  211. InputStream input = null;
  212. OutputStream output = null;
  213. try {
  214. input = socket.getInputStream();
  215. output = socket.getOutputStream();
  216. } catch (IOException e) {
  217. e.printStackTrace();
  218. }
  219. this.inputStream = input;
  220. this.outputStream = output;
  221. }
  222. public void run() {
  223. byte[] buff = new byte[1024];
  224. int bytes;
  225. while (true) {
  226. try {
  227. bytes = inputStream.read(buff);
  228. String str = new String(buff, "ISO-8859-1");
  229. str = str.substring(0, bytes);
  230. Log.e("recv", str);
  231.  
  232. Message message=handler.obtainMessage();
  233. message.obj=str;
  234. handler.sendMessage(message);
  235. } catch (IOException e) {
  236. e.printStackTrace();
  237. break;
  238. }
  239. }
  240. }
  241. public void write(byte[] bytes) {
  242. try {
  243. outputStream.write(bytes);
  244. } catch (IOException e) {
  245. e.printStackTrace();
  246. }
  247. }
  248. public void cancel() {
  249. try {
  250. socket.close();
  251. } catch (IOException e) {
  252. e.printStackTrace();
  253. }
  254. }
  255. }
  256. Handler handler=new Handler(){
  257. @Override
  258. public void handleMessage(Message msg) {
  259.  
  260. String s= (String) msg.obj;
  261. message=message+s;
  262. if(message.contains("RTS_Mon->")){
  263. textView.setText(message);
  264.  
  265. }
  266. }
  267. };
  268.  
  269. }

3.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:paddingBottom="@dimen/activity_vertical_margin"
  7. android:paddingLeft="@dimen/activity_horizontal_margin"
  8. android:paddingRight="@dimen/activity_horizontal_margin"
  9. android:paddingTop="@dimen/activity_vertical_margin"
  10. tools:context="myapplication.com.myapplicationble.MainActivity">
  11.  
  12. <TextView
  13. android:id="@+id/textView"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="Hello World!" />
  17. <EditText
  18. android:layout_below="@+id/textView"
  19. android:id="@+id/edit"
  20. android:layout_width="match_parent"
  21. android:textColor="@color/hei"
  22. android:layout_height="wrap_content"/>
  23. <Button
  24. android:layout_height="wrap_content"
  25. android:layout_width="match_parent"
  26. android:id="@+id/button"
  27. android:layout_below="@+id/edit"
  28. android:text="send"
  29. />
  30. <Button
  31.  
  32. android:layout_height="wrap_content"
  33. android:layout_width="match_parent"
  34. android:id="@+id/button1"
  35. android:layout_below="@+id/button"
  36. android:text="lianjie"
  37. />
  38.  
  39. </RelativeLayout>

code:链接:http://pan.baidu.com/s/1jHAL0WI 密码:xvss

Android蓝牙2.0连接以及数据接收发送的更多相关文章

  1. Android蓝牙连接以及数据接收发送

    1.加入权限 <uses-feature android:name="android.hardware.bluetooth_le" android:required=&quo ...

  2. Android 蓝牙4.0的连接和通讯

    1.加入权限 <uses-sdk android:minSdkVersion=" android:targetSdkVersion="/> <uses-featu ...

  3. ym——物联网入口之中的一个Android蓝牙4.0

    转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 假设还有同学不知道蓝牙4.0能够做什么请查看Android+蓝牙 4.0 将带来什么? ...

  4. Android 蓝牙4.0 BLE

    Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是蓝牙4.0的核心Profil ...

  5. android 蓝牙4.0 开发介绍

    最近一直在研究一个蓝牙功能 由于本人是菜鸟  学起来比较忙 一直搞了好久才弄懂 , 网上对蓝牙4.0也就是几个个dome 抄来抄去,全是英文注解 , 对英语不好的朋友来说 真是硬伤 , 一些没必要的描 ...

  6. Android 蓝牙4.0 BLE (onServicesDiscovered 返回 status 是 129,133时)

    Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说android 4.3+, API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是 ...

  7. .Net2.0连接PG数据注意事项

    .Net2.0连接PG数据注意事项 第一次用.net操作PG[.NET2.0] 一:Npgsql版本问题 1:如果是.net2.0  建议用2.0.11.0[NuGet搜索npgsql第一个的最低版本 ...

  8. android 蓝牙4.0多通道

    很久没记录东西了,前段时间研究了一哈android4.0控制多个外设的情况,注意,需要使用android版本4.3以上,蓝牙4.0及以上. 我这里使用的控制蓝牙灯泡,使用android4.3的手机,手 ...

  9. Android 蓝牙( Bluetooth)耳机连接分析及实现

    Android 实现了对Headset 和Handsfree 两种profile 的支持.其实现核心是BluetoothHeadsetService,在PhoneApp 创建的时候会启动它. if ( ...

随机推荐

  1. [Intermediate Algorithm] - Spinal Tap Case

    题目 将字符串转换为 spinal case.Spinal case 是 all-lowercase-words-joined-by-dashes 这种形式的,也就是以连字符连接所有小写单词. 提示 ...

  2. SaltStact自动化运维工具02

     Grains基础:• Grains是saltstack最重要的组件之一• 存储minion端的基本信息,这些信息一般都是静态的,如CPU.内核.操作系统等• Grains存储在minion本地• 管 ...

  3. C#学习 第十节

    操作符(operator) 1.操作符的概览 从上到下优先级依次减弱: 2.操作符的本质 操作符的本质是函数的简记法: 计算机的操作符不能脱离与它关联的数据类型: 3.操作符的优先级 可以使用括号 4 ...

  4. 【模板】 最大流模板(ISAP)

    题目描述 如题,给出一个网络图,以及其源点和汇点,求出其网络最大流. 输入输出格式 输入格式: 第一行包含四个正整数N.M.S.T,分别表示点的个数.有向边的个数.源点序号.汇点序号. 接下来M行每行 ...

  5. [剑指offer] 49. 丑数

    通俗易懂的解释: 首先从丑数的定义我们知道,一个丑数的因子只有2,3,5,那么丑数p = 2 ^ x * 3 ^ y * 5 ^ z,换句话说一个丑数一定由另一个丑数乘以2或者乘以3或者乘以5得到,那 ...

  6. 《黑白团团队》第八次团队作业:Alpha冲刺 第二天

    项目 内容 作业课程地址 任课教师首页链接 作业要求 团队项目 填写团队名称 黑白团团队 填写具体目标 认真负责,完成项目 团队项目Github仓库地址链接. 第二天 日期:2019/6/16 成员 ...

  7. Ajax接收json响应

    json?  Json和xml比较  Ajax如何使用JSON  Ajax接收json响应案例 什么是json?JSON (JavaScript Object Notation) 是一种轻量级的 ...

  8. Linux用户管理案例(第二版)

    批量添加用户 1.按照/etc/passwd文件格式编写用户信息文件users.info xiaofang01::1001:503::/home/xiaofang01:/bin/bash  #注意不能 ...

  9. [HTML5] Semantics for accessibility

    For example, when we use checkbox, if we do like this: <div class="inline-control sign-up co ...

  10. Spring+MyBatis双数据库配置

    Spring+MyBatis双数据库配置 近期项目中遇到要调用其它数据库的情况.本来仅仅使用一个MySQL数据库.但随着项目内容越来越多,逻辑越来越复杂. 原来一个数据库已经不够用了,须要分库分表.所 ...