Android 蓝牙2.0的连接通讯
来源:互联网 发布:国密sm2算法 编辑:程序博客网 时间:2024/05/29 16:48
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.修改 接受数据线程
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(); } } }
4.代码修改完成
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); } } };}
5.布局
<?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>
6. 实现图
7.code:
code:链接:http://pan.baidu.com/s/1jHAL0WI 密码:xvss
0 0
- Android 蓝牙2.0的连接通讯
- Android 蓝牙设备通讯的开发(配对/连接/传输数据)
- Android蓝牙聊天,蓝牙通讯
- android 手机与蓝牙设备的通讯
- 一个关于android蓝牙通讯的问题
- android app与蓝牙设备之间连接与通讯
- android蓝牙通讯
- Android蓝牙通讯
- android蓝牙通讯
- android蓝牙通讯
- Android蓝牙通讯模块
- Android蓝牙通讯
- Android蓝牙串口通讯
- Android 蓝牙遥控器的连接
- Android蓝牙通讯(三)————蓝牙通讯的实现
- 蓝牙通讯的开发
- android 蓝牙通讯实现手机蓝牙的开启,并扫描附近可见的蓝牙设备
- Android 与蓝牙串口通讯
- Spark SQL与DataFrame
- android TV架构启动流程分析(一)
- XUtils的bitmap模块
- Hello, World !
- 立体视觉标定和校正
- Android 蓝牙2.0的连接通讯
- 404
- Nodejs基于mongoose模块的用法
- OSI七层模型
- Oracle——用户、角色和权限信息的视图总结
- 【Struts2】Action接收参数的三种方式
- js中前台数据左右切换移动
- 为什么在函数的声明后面还有一个 const? 如:void fun() const;
- select2的搜索框不能输入搜索内容