Android蓝牙2.0连接以及数据接收发送
1.加入权限
- <uses-feature
- android:name="android.hardware.bluetooth_le"
- android:required="true" />
- <uses-permission android:name="android.permission.BLUETOOTH" />
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2.代码:
- package myapplication.com.myapplicationble;
- import android.app.Service;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothServerSocket;
- import android.bluetooth.BluetoothSocket;
- import android.content.Context;
- import android.content.Intent;
- import android.os.AsyncTask;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.PopupMenu;
- import android.widget.PopupWindow;
- import android.widget.TextView;
- import android.widget.Toast;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.Socket;
- import java.util.UUID;
- public class MainActivity extends AppCompatActivity {
- private BluetoothAdapter BA;
- BluetoothServerSocket mmServerSocket;
- private static String address = "20:16:09:26:81:80"; // <==应填写蓝牙串口模块的蓝牙地址。
- private BluetoothSocket btSocket = null;
- private OutputStream outStream = null;
- public InputStream inStream = null;
- EditText editText;
- TextView textView;
- Button button, button1;
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- initView();
- }
- /**
- * 连接蓝牙
- * **/
- public void connect() {
- BA = BluetoothAdapter.getDefaultAdapter();
- BluetoothDevice device = BA.getRemoteDevice(address);
- // pairedDevices = BA.getBondedDevices();
- try {
- btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
- // new ReceiveDatas(btSocket).start();
- } catch (IOException e) {
- }
- BA.cancelDiscovery();
- try {
- btSocket.connect();
- // String s="sm";
- outStream = btSocket.getOutputStream();
- // outStream.write(s.getBytes());
- //outStream.write(0x41);
- inStream = btSocket.getInputStream();
- while (true){
- byte[] buffer = new byte[100];
- int count = inStream.read(buffer);
- int a= inStream.available();
- String ss= new String(buffer, 0, count, "utf-8");
- System.out.println("***A"+ss);
// 输出信息缺少……不全,占时不会- }
- } catch (IOException e) {
- }
- try {
- // btSocket.close();
- } catch (Exception e2) {
- // Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
- }
- }
- public void initView() {
- editText = (EditText) findViewById(R.id.edit);
- textView = (TextView) findViewById(R.id.textView);
- button = (Button) findViewById(R.id.button);
- button1 = (Button) findViewById(R.id.button1);
- BA = BluetoothAdapter.getDefaultAdapter();
- /**
- * 连接蓝牙
- * */
- button1.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- System.out.println("***11");
- as();
- }
- });
- /**
- * 发送信息
- * **/
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- String s = editText.getText().toString();
- try {
- // outStream.write(s.getBytes()); 发送数据
- outStream = btSocket.getOutputStream();
- inStream=btSocket.getInputStream();
- outStream.write("sm".getBytes());
- outStream.write("\r\n".getBytes());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- }
- /**
- *
- * 连接蓝牙
- * **/
- public void as() {
- new AsyncTask() {
- @Override
- protected String doInBackground(Object[] params) {
- connect();
- return null;
- }
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
- @Override
- protected void onPostExecute(Object o) {
- super.onPostExecute(o);
- Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
- }
- }.execute();
- }
- }
3.操作图
<1>连接后发送数据oooo到蓝牙,接收端显示oooo
<2> 终端发送数据,手机端打印出数据ooooui [oooo]是打印的字符串,ui为接收的数据
修改——-->:
接受数据:
- 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);
- Message message=handler.obtainMessage();
- message.obj=str;
- handler.sendMessage(message);
- } 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();
- }
- }
- }
---------------------------------------------------------------------------------------------------------------------------------------------------------
完成后代码:
1.权限:
- <uses-feature
- android:name="android.hardware.bluetooth_le"
- android:required="true" />
- <uses-permission android:name="android.permission.BLUETOOTH" />
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2.Activity:
- package myapplication.com.myapplicationble;
- import android.app.Service;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothServerSocket;
- import android.bluetooth.BluetoothSocket;
- import android.content.Context;
- import android.content.Intent;
- import android.os.AsyncTask;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.PopupMenu;
- import android.widget.PopupWindow;
- import android.widget.TextView;
- import android.widget.Toast;
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.Socket;
- import java.util.ArrayList;
- import java.util.UUID;
- public class MainActivity extends AppCompatActivity {
- private BluetoothAdapter BA;
- BluetoothServerSocket mmServerSocket;
- String message="";
- private static String address = "20:16:09:26:81:80"; // <==应填写蓝牙串口模块的蓝牙地址。
- private BluetoothSocket btSocket = null;
- private OutputStream outStream = null;
- public InputStream inStream = null;
- EditText editText;
- TextView textView;
- Button button, button1;
- boolean BluetoothFlag;
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- initView();
- }
- /**
- * 连接蓝牙
- **/
- public void connect() {
- BA = BluetoothAdapter.getDefaultAdapter();
- BluetoothDevice device = BA.getRemoteDevice(address);
- // pairedDevices = BA.getBondedDevices();
- try {
- btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
- } catch (IOException e) {
- }
- BA.cancelDiscovery();
- try {
- btSocket.connect();
- // String s="sm";
- outStream = btSocket.getOutputStream();
- //outStream.write(s.getBytes());
- //outStream.write(0x41);
- inStream = btSocket.getInputStream();
- // while (true){
- // byte[] buffer = new byte[1];
- // int length = 0;
- // byte bb = 0;
- // String line = null;
- // ArrayList<Byte> list = new ArrayList<Byte>();
- // while (inStream.read(buffer) == -1) {
- // try {
- // Thread.sleep(100);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- // System.out.print("-->" +inStream.read(buffer));
- // }
- // }
- /***
- * 1
- * **/
- // while (true) {
- //
- // if(inStream.available()>=0){
- // byte[] buffer = new byte[1024];
- // int count = inStream.read(buffer);
- // // System.out.println("***MAX:" + a);
- // String ss = new String(buffer, 0, count, "utf-8");
- // System.out.println("*--" + ss);
- // }
- //
- // }
- /****
- * 2
- * */
- // BluetoothFlag = true;
- // MyThread bluetoothThread = new MyThread();
- // bluetoothThread.start();
- /***
- *
- * 3
- * */
- ConnectedThread connectedThread = new ConnectedThread(btSocket);
- connectedThread.start();
- } catch (IOException e) {
- }
- try {
- // btSocket.close();
- } catch (Exception e2) {
- // Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
- }
- }
- public void initView() {
- editText = (EditText) findViewById(R.id.edit);
- textView = (TextView) findViewById(R.id.textView);
- button = (Button) findViewById(R.id.button);
- button1 = (Button) findViewById(R.id.button1);
- BA = BluetoothAdapter.getDefaultAdapter();
- /**
- * 连接蓝牙
- * */
- button1.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- System.out.println("***11");
- as();
- }
- });
- /**
- * 发送信息
- * **/
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- String s = editText.getText().toString();
- try {
- outStream = btSocket.getOutputStream();
- inStream = btSocket.getInputStream();
- // outStream.write("\r\n".getBytes());
- outStream.write("sm".getBytes());
- outStream.write("\r\n".getBytes());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- }
- /**
- * 连接蓝牙
- **/
- public void as() {
- new AsyncTask() {
- @Override
- protected String doInBackground(Object[] params) {
- connect();
- return null;
- }
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
- @Override
- protected void onPostExecute(Object o) {
- super.onPostExecute(o);
- Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
- }
- }.execute();
- }
- /**
- * 在接受不到数据
- * **/
- 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);
- Message message=handler.obtainMessage();
- message.obj=str;
- handler.sendMessage(message);
- } 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();
- }
- }
- }
- Handler handler=new Handler(){
- @Override
- public void handleMessage(Message msg) {
- String s= (String) msg.obj;
- message=message+s;
- if(message.contains("RTS_Mon->")){
- textView.setText(message);
- }
- }
- };
- }
3.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="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context="myapplication.com.myapplicationble.MainActivity">
- <TextView
- android:id="@+id/textView"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World!" />
- <EditText
- android:layout_below="@+id/textView"
- android:id="@+id/edit"
- android:layout_width="match_parent"
- android:textColor="@color/hei"
- android:layout_height="wrap_content"/>
- <Button
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/button"
- android:layout_below="@+id/edit"
- android:text="send"
- />
- <Button
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/button1"
- android:layout_below="@+id/button"
- android:text="lianjie"
- />
- </RelativeLayout>
code:链接:http://pan.baidu.com/s/1jHAL0WI 密码:xvss
Android蓝牙2.0连接以及数据接收发送的更多相关文章
- Android蓝牙连接以及数据接收发送
1.加入权限 <uses-feature android:name="android.hardware.bluetooth_le" android:required=&quo ...
- Android 蓝牙4.0的连接和通讯
1.加入权限 <uses-sdk android:minSdkVersion=" android:targetSdkVersion="/> <uses-featu ...
- ym——物联网入口之中的一个Android蓝牙4.0
转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 假设还有同学不知道蓝牙4.0能够做什么请查看Android+蓝牙 4.0 将带来什么? ...
- Android 蓝牙4.0 BLE
Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是蓝牙4.0的核心Profil ...
- android 蓝牙4.0 开发介绍
最近一直在研究一个蓝牙功能 由于本人是菜鸟 学起来比较忙 一直搞了好久才弄懂 , 网上对蓝牙4.0也就是几个个dome 抄来抄去,全是英文注解 , 对英语不好的朋友来说 真是硬伤 , 一些没必要的描 ...
- Android 蓝牙4.0 BLE (onServicesDiscovered 返回 status 是 129,133时)
Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说android 4.3+, API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是 ...
- .Net2.0连接PG数据注意事项
.Net2.0连接PG数据注意事项 第一次用.net操作PG[.NET2.0] 一:Npgsql版本问题 1:如果是.net2.0 建议用2.0.11.0[NuGet搜索npgsql第一个的最低版本 ...
- android 蓝牙4.0多通道
很久没记录东西了,前段时间研究了一哈android4.0控制多个外设的情况,注意,需要使用android版本4.3以上,蓝牙4.0及以上. 我这里使用的控制蓝牙灯泡,使用android4.3的手机,手 ...
- Android 蓝牙( Bluetooth)耳机连接分析及实现
Android 实现了对Headset 和Handsfree 两种profile 的支持.其实现核心是BluetoothHeadsetService,在PhoneApp 创建的时候会启动它. if ( ...
随机推荐
- [Intermediate Algorithm] - Spinal Tap Case
题目 将字符串转换为 spinal case.Spinal case 是 all-lowercase-words-joined-by-dashes 这种形式的,也就是以连字符连接所有小写单词. 提示 ...
- SaltStact自动化运维工具02
Grains基础:• Grains是saltstack最重要的组件之一• 存储minion端的基本信息,这些信息一般都是静态的,如CPU.内核.操作系统等• Grains存储在minion本地• 管 ...
- C#学习 第十节
操作符(operator) 1.操作符的概览 从上到下优先级依次减弱: 2.操作符的本质 操作符的本质是函数的简记法: 计算机的操作符不能脱离与它关联的数据类型: 3.操作符的优先级 可以使用括号 4 ...
- 【模板】 最大流模板(ISAP)
题目描述 如题,给出一个网络图,以及其源点和汇点,求出其网络最大流. 输入输出格式 输入格式: 第一行包含四个正整数N.M.S.T,分别表示点的个数.有向边的个数.源点序号.汇点序号. 接下来M行每行 ...
- [剑指offer] 49. 丑数
通俗易懂的解释: 首先从丑数的定义我们知道,一个丑数的因子只有2,3,5,那么丑数p = 2 ^ x * 3 ^ y * 5 ^ z,换句话说一个丑数一定由另一个丑数乘以2或者乘以3或者乘以5得到,那 ...
- 《黑白团团队》第八次团队作业:Alpha冲刺 第二天
项目 内容 作业课程地址 任课教师首页链接 作业要求 团队项目 填写团队名称 黑白团团队 填写具体目标 认真负责,完成项目 团队项目Github仓库地址链接. 第二天 日期:2019/6/16 成员 ...
- Ajax接收json响应
json? Json和xml比较 Ajax如何使用JSON Ajax接收json响应案例 什么是json?JSON (JavaScript Object Notation) 是一种轻量级的 ...
- Linux用户管理案例(第二版)
批量添加用户 1.按照/etc/passwd文件格式编写用户信息文件users.info xiaofang01::1001:503::/home/xiaofang01:/bin/bash #注意不能 ...
- [HTML5] Semantics for accessibility
For example, when we use checkbox, if we do like this: <div class="inline-control sign-up co ...
- Spring+MyBatis双数据库配置
Spring+MyBatis双数据库配置 近期项目中遇到要调用其它数据库的情况.本来仅仅使用一个MySQL数据库.但随着项目内容越来越多,逻辑越来越复杂. 原来一个数据库已经不够用了,须要分库分表.所 ...