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蓝牙连接以及数据接收发送的更多相关文章

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

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

  2. nodejs实现Websocket的数据接收发送

    在去年的时候,写过一篇关于websocket的博文:http://www.cnblogs.com/axes/p/3586132.html ,里面主要是借助了nodejs-websocket这个插件,后 ...

  3. Android蓝牙连接自动测试工具

    蓝牙连接自动测试工具 1.需求产生 开发不按着需求走都是耍流氓且浪费时间.此工具的需求产生是研发人员在开发产品时涉及到蓝牙驱动和安卓蓝牙两个东西.但是呢,蓝牙不太稳定,那么工作来了.就需要研发人员一边 ...

  4. Android 低功耗蓝牙的多设备连接与数据接收,简单实现

    在网络层,互联网提供所有应用程序都要使用的两种类型的服务,尽管目前理解这些服务的细节并不重要,但在所有TCP/IP概述中,都不能忽略他们: 无连接分组交付服务(Connectionless Packe ...

  5. android 蓝牙连接与通讯(Bluetooth)

    最近做了一个小项目,关于蓝牙的一个智能硬件.其中涉及到了蓝牙模块的操作.特记下蓝牙模块的操作过程.只记录下关于蓝牙部分的操作,具体业务逻辑不涉及其中.重点是记录下蓝牙的扫描.链接.通讯. 在使用蓝牙模 ...

  6. android 蓝牙连接端(客户端)封装

    0.权限  AndroidManifest.xml <uses-permission android:name="android.permission.BLUETOOTH"/ ...

  7. android 蓝牙编程重点---如何发送和接收16进制数据

    最近的android蓝牙开发项目也逐渐接近尾声,基本的功能都已经完成,只剩下界面的设计.现在真的是舒了一口气! 作为编程学习经验只有1年的菜鸟,这是我独自完成的商业性产品,而且还是涉及到与单片机蓝牙模 ...

  8. Android Wear开发 - 数据通讯 - 第二节 : 数据的发送与接收

    本节由介绍3种数据的发送接收:1.Data Items : 比特类型数据,限制100KB以内2.Assets : 资源类型数据,大小无上限3.Message : 发送消息,触发指令 http://de ...

  9. Android蓝牙BLE开发,扫描、连接、发送和读取信息;

    1.BLE开发权限 Android蓝牙BLE开发须打开蓝牙权限和6.0位置权限: <uses-permission android:name="android.permission.B ...

随机推荐

  1. 如何在ubuntu中启用SSH服务

    如何在ubuntu14.04 中启用SSH服务 开篇科普:  SSH 为 Secure Shell 的缩写,由 IETF 的网络工作小组(Network Working Group)所制定:SSH 为 ...

  2. php常用时间戳记录

    <?php echo '<br/>'; //php获取今日开始时间戳和结束时间戳 echo "今天"; echo '<br/>'; $beginTod ...

  3. 无法访问 IIS 元数据库。您没有足够的特权访问计算机上的 IIS 网站

    我是WIN10+VS2015  之前用的是VS2012     后来卸载了VS2012 就出现了这个错误,请问该如何解决 在VS的图标上 按右键用管理员(Administrator)运行

  4. Autofac.Integration.Owin

    public static IAppBuilder UseAutofacMiddleware(this IAppBuilder app, ILifetimeScope container) { if ...

  5. Autofac.Integration.Mvc分析

    Autofac.Integration.Mvc static ILifetimeScope LifetimeScope { get { return (ILifetimeScope)HttpConte ...

  6. myeclipse工程当中的.classpath 和.project文件什么作用?

    .project是项目文件,项目的结构都在其中定义,比如lib的位置,src的位置,classes的位置.classpath的位置定义了你这个项目在编译时所使用的$CLASSPATH .classpa ...

  7. php empty函数

    empty — 检查一个变量是否为空. 当一个变量并不存在,或者它的值等同于FALSE,那么它就会被认为不存在.如果变量不存在的话,empty()并不会产生警告. 返回值: 当var存在,并且是一个非 ...

  8. Python开发【第十四篇】:Web框架本质

    Web框架本质 众所周知,对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...

  9. Spring入门_03_构造注入

    实体类 Student.java package com.umgsai.spring.entity; import java.util.Date; public class Student { pri ...

  10. 从HTML原型到jsp页面完美转型攻略(教你即使不会写代码也能弄出漂亮的网页)

    大家都知道软件项目(web)开发之前都要先做原型设计,而我们使用的比较多的一款原型设计软件就是Axure rp了.在Axure rp上画原型不需要任何编码能力,而且生成的原型可以在浏览器上运行.除了没 ...