android 蓝牙通讯编程 备忘

 

1.启动App后:

判断->蓝牙是否打开(所有功能必须在打牙打开的情况下才能用)

已打开: 启动代码中的蓝牙通讯Service

未打开: 发布 打开蓝牙意图(系统),根据Activity返回进场操作

          打开成功,启动代码中的蓝牙通讯Service

          用户点back或失败 退出App

 

2.蓝牙设备列表:

2.1显示已经配对列表:

注册蓝牙设备发现广播

   广播中将发现的设备添加到列表
2.2当用户点Scan时,启动蓝牙发现,发现设备时会收到广播事件。

2.3用户点某个条目时,将改条目的 MAC返回给主Activity(调用了startActivityForResult的Activity)

 

3.使设备可发现

    private void ensureDiscoverable() {Log.d(TAG, "ensure discoverable");if (mBluetoothAdapter.getScanMode() !=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);startActivity(discoverableIntent);}}
View Code

 4.蓝牙socket操作

/** Copyright (C) 2009 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package com.example.android.BluetoothChat;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;/*** This class does all the work for setting up and managing Bluetooth* connections with other devices. It has a thread that listens for* incoming connections, a thread for connecting with a device, and a* thread for performing data transmissions when connected.*/
public class BluetoothChatService {// Debuggingprivate static final String TAG = "BluetoothChatService";private static final boolean D = true;// Name for the SDP record when creating server socketprivate static final String NAME_SECURE = "BluetoothChatSecure";private static final String NAME_INSECURE = "BluetoothChatInsecure";// Unique UUID for this applicationprivate static final UUID MY_UUID_SECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");private static final UUID MY_UUID_INSECURE =UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");// Member fieldsprivate final BluetoothAdapter mAdapter;private final Handler mHandler;private AcceptThread mSecureAcceptThread;private AcceptThread mInsecureAcceptThread;private ConnectThread mConnectThread;private ConnectedThread mConnectedThread;private int mState;// Constants that indicate the current connection statepublic static final int STATE_NONE = 0;       // we're doing nothingpublic static final int STATE_LISTEN = 1;     // now listening for incoming connectionspublic static final int STATE_CONNECTING = 2; // now initiating an outgoing connectionpublic static final int STATE_CONNECTED = 3;  // now connected to a remote device/*** Constructor. Prepares a new BluetoothChat session.* @param context  The UI Activity Context* @param handler  A Handler to send messages back to the UI Activity*/public BluetoothChatService(Context context, Handler handler) {mAdapter = BluetoothAdapter.getDefaultAdapter();mState = STATE_NONE;mHandler = handler;}/*** Set the current state of the chat connection* @param state  An integer defining the current connection state*/private synchronized void setState(int state) {if (D) Log.d(TAG, "setState() " + mState + " -> " + state);mState = state;// Give the new state to the Handler so the UI Activity can updatemHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();}/*** Return the current connection state. */public synchronized int getState() {return mState;}/*** Start the chat service. Specifically start AcceptThread to begin a* session in listening (server) mode. Called by the Activity onResume() */public synchronized void start() {if (D) Log.d(TAG, "start");// Cancel any thread attempting to make a connectionif (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}// Cancel any thread currently running a connectionif (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}setState(STATE_LISTEN);// Start the thread to listen on a BluetoothServerSocketif (mSecureAcceptThread == null) {mSecureAcceptThread = new AcceptThread(true);mSecureAcceptThread.start();}if (mInsecureAcceptThread == null) {mInsecureAcceptThread = new AcceptThread(false);mInsecureAcceptThread.start();}}/*** Start the ConnectThread to initiate a connection to a remote device.* @param device  The BluetoothDevice to connect* @param secure Socket Security type - Secure (true) , Insecure (false)*/public synchronized void connect(BluetoothDevice device, boolean secure) {if (D) Log.d(TAG, "connect to: " + device);// Cancel any thread attempting to make a connectionif (mState == STATE_CONNECTING) {if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}}// Cancel any thread currently running a connectionif (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}// Start the thread to connect with the given devicemConnectThread = new ConnectThread(device, secure);mConnectThread.start();setState(STATE_CONNECTING);}/*** Start the ConnectedThread to begin managing a Bluetooth connection* @param socket  The BluetoothSocket on which the connection was made* @param device  The BluetoothDevice that has been connected*/public synchronized void connected(BluetoothSocket socket, BluetoothDevicedevice, final String socketType) {if (D) Log.d(TAG, "connected, Socket Type:" + socketType);// Cancel the thread that completed the connectionif (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}// Cancel any thread currently running a connectionif (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}// Cancel the accept thread because we only want to connect to one deviceif (mSecureAcceptThread != null) {mSecureAcceptThread.cancel();mSecureAcceptThread = null;}if (mInsecureAcceptThread != null) {mInsecureAcceptThread.cancel();mInsecureAcceptThread = null;}// Start the thread to manage the connection and perform transmissionsmConnectedThread = new ConnectedThread(socket, socketType);mConnectedThread.start();// Send the name of the connected device back to the UI ActivityMessage msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);Bundle bundle = new Bundle();bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());msg.setData(bundle);mHandler.sendMessage(msg);setState(STATE_CONNECTED);}/*** Stop all threads*/public synchronized void stop() {if (D) Log.d(TAG, "stop");if (mConnectThread != null) {mConnectThread.cancel();mConnectThread = null;}if (mConnectedThread != null) {mConnectedThread.cancel();mConnectedThread = null;}if (mSecureAcceptThread != null) {mSecureAcceptThread.cancel();mSecureAcceptThread = null;}if (mInsecureAcceptThread != null) {mInsecureAcceptThread.cancel();mInsecureAcceptThread = null;}setState(STATE_NONE);}/*** Write to the ConnectedThread in an unsynchronized manner* @param out The bytes to write* @see ConnectedThread#write(byte[])*/public void write(byte[] out) {// Create temporary object
        ConnectedThread r;// Synchronize a copy of the ConnectedThreadsynchronized (this) {if (mState != STATE_CONNECTED) return;r = mConnectedThread;}// Perform the write unsynchronized
        r.write(out);}/*** Indicate that the connection attempt failed and notify the UI Activity.*/private void connectionFailed() {// Send a failure message back to the ActivityMessage msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);Bundle bundle = new Bundle();bundle.putString(BluetoothChat.TOAST, "Unable to connect device");msg.setData(bundle);mHandler.sendMessage(msg);// Start the service over to restart listening modeBluetoothChatService.this.start();}/*** Indicate that the connection was lost and notify the UI Activity.*/private void connectionLost() {// Send a failure message back to the ActivityMessage msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);Bundle bundle = new Bundle();bundle.putString(BluetoothChat.TOAST, "Device connection was lost");msg.setData(bundle);mHandler.sendMessage(msg);// Start the service over to restart listening modeBluetoothChatService.this.start();}/*** This thread runs while listening for incoming connections. It behaves* like a server-side client. It runs until a connection is accepted* (or until cancelled).*/private class AcceptThread extends Thread {// The local server socketprivate final BluetoothServerSocket mmServerSocket;private String mSocketType;public AcceptThread(boolean secure) {BluetoothServerSocket tmp = null;mSocketType = secure ? "Secure":"Insecure";// Create a new listening server sockettry {if (secure) {tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,MY_UUID_SECURE);} else {tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, MY_UUID_INSECURE);}} catch (IOException e) {Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);}mmServerSocket = tmp;}public void run() {if (D) Log.d(TAG, "Socket Type: " + mSocketType +"BEGIN mAcceptThread" + this);setName("AcceptThread" + mSocketType);BluetoothSocket socket = null;// Listen to the server socket if we're not connectedwhile (mState != STATE_CONNECTED) {try {// This is a blocking call and will only return on a// successful connection or an exceptionsocket = mmServerSocket.accept();} catch (IOException e) {Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);break;}// If a connection was acceptedif (socket != null) {synchronized (BluetoothChatService.this) {switch (mState) {case STATE_LISTEN:case STATE_CONNECTING:// Situation normal. Start the connected thread.
                            connected(socket, socket.getRemoteDevice(),mSocketType);break;case STATE_NONE:case STATE_CONNECTED:// Either not ready or already connected. Terminate new socket.try {socket.close();} catch (IOException e) {Log.e(TAG, "Could not close unwanted socket", e);}break;}}}}if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);}public void cancel() {if (D) Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);try {mmServerSocket.close();} catch (IOException e) {Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);}}}/*** This thread runs while attempting to make an outgoing connection* with a device. It runs straight through; the connection either* succeeds or fails.*/private class ConnectThread extends Thread {private final BluetoothSocket mmSocket;private final BluetoothDevice mmDevice;private String mSocketType;public ConnectThread(BluetoothDevice device, boolean secure) {mmDevice = device;BluetoothSocket tmp = null;mSocketType = secure ? "Secure" : "Insecure";// Get a BluetoothSocket for a connection with the// given BluetoothDevicetry {if (secure) {tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);} else {tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);}} catch (IOException e) {Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);}mmSocket = tmp;}public void run() {Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);setName("ConnectThread" + mSocketType);// Always cancel discovery because it will slow down a connection
            mAdapter.cancelDiscovery();// Make a connection to the BluetoothSockettry {// This is a blocking call and will only return on a// successful connection or an exception
                mmSocket.connect();} catch (IOException e) {// Close the sockettry {mmSocket.close();} catch (IOException e2) {Log.e(TAG, "unable to close() " + mSocketType +" socket during connection failure", e2);}connectionFailed();return;}// Reset the ConnectThread because we're donesynchronized (BluetoothChatService.this) {mConnectThread = null;}// Start the connected thread
            connected(mmSocket, mmDevice, mSocketType);}public void cancel() {try {mmSocket.close();} catch (IOException e) {Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);}}}/*** This thread runs during a connection with a remote device.* It handles all incoming and outgoing transmissions.*/private class ConnectedThread extends Thread {private final BluetoothSocket mmSocket;private final InputStream mmInStream;private final OutputStream mmOutStream;public ConnectedThread(BluetoothSocket socket, String socketType) {Log.d(TAG, "create ConnectedThread: " + socketType);mmSocket = socket;InputStream tmpIn = null;OutputStream tmpOut = null;// Get the BluetoothSocket input and output streamstry {tmpIn = socket.getInputStream();tmpOut = socket.getOutputStream();} catch (IOException e) {Log.e(TAG, "temp sockets not created", e);}mmInStream = tmpIn;mmOutStream = tmpOut;}public void run() {Log.i(TAG, "BEGIN mConnectedThread");byte[] buffer = new byte[1024];int bytes;String buffString="";// Keep listening to the InputStream while connectedwhile (true) {try {// Read from the InputStreambytes = mmInStream.read(buffer);String msg=new String(buffer,0,bytes);buffString +=msg;int indexOfNewLine= buffString.indexOf("\n");if(indexOfNewLine>=0){String frameString= buffString.substring(0, indexOfNewLine+1);buffString=buffString.substring(indexOfNewLine+1);mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, frameString).sendToTarget();}if(buffString.length()>1024){buffString="";}// Send the obtained bytes to the UI Activity
//                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
//                            .sendToTarget();
                    } catch (IOException e) {Log.e(TAG, "disconnected", e);connectionLost();break;}}}/*** Write to the connected OutStream.* @param buffer  The bytes to write*/public void write(byte[] buffer) {try {mmOutStream.write(buffer);// Share the sent message back to the UI ActivitymHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();} catch (IOException e) {Log.e(TAG, "Exception during write", e);}}public void cancel() {try {mmSocket.close();} catch (IOException e) {Log.e(TAG, "close() of connect socket failed", e);}}}
}
View Code

 

懒样状态图:

 

转载于:https://www.cnblogs.com/wdfrog/p/4378299.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/259158.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java 程序执行后 强制gc_GC 设计与停顿

(给ImportNew加星标,提高Java技能)编译:唐尤华链接:shipilev.net/jvm/anatomy-quarks/3-gc-design-and-pauses/1. 写在前面“[JVM 解剖公园][1]”是一个持续更新的系列迷你博客,阅读每篇文章一般需要5到10分钟。限于篇幅&#xff…

【ASP.NET Web API2】初识Web API

Web Api 是什么? MSDN:ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务 百度百科:Web API是网络应用程序接口。 个人理解:Web API 是提供给多种…

三星s8怎么分屏操作_三星手机该怎么玩?了解完这几点用机技巧,可以轻车熟路了!...

其实对于三星这个手机品牌,我还是很佩服的。虽然近些年来,三星在国内的市场份额日渐变少,但是在国内的影响力依然尚存。毕竟三星手机在某些方面还是很有优势的,特别是旗舰系列机型深受消费者喜爱。接下来,笔者就跟大家…

二维数组的指针复习

最近一次的考试都是指针,真是给我深深上了一课,所以我特此复习一下指针方面的知识。二维数组的指针 int a[3][4] {{1,3,5,7},{9,11,13,15},{17,19,21,23}}; 下面通过一个表来做详细的说明: 访问二维数组,有两种方法,一…

称重的问题

给你8颗小石头和一架托盘天平。有7颗石头的重量是一样的,另外一颗比其他石头略重;除此之外,这些石头完全没有分别。你不得假设那颗重头到底比其他的石头重了多少。请问:最少要称量几次,你才能把那颗较重的石头找出来&a…

TIF图像文件的读取(c++代码)

一 TIF图像介绍 TIFF是最复杂的一种位图文件格式。TIFF是基于标记的文件格式,它广泛地应用于对图像质量要求较高的图像的存储与转换。由于它的结构灵活和包容性大,它已成为图像文件格式的一种标准,绝大多数图像系统都支持这种格式。 TIFF 是一…

g menu i meun_长沙话读“这里”,到底是阁(gó)里还是该(gái)里

“带笼子”、“打抱秋”……这些地道的长沙话,长沙人,你有多久没听过了?/ 长沙人,你还记得长沙话吗 / “去了很多地方,最后还是回到了长沙”“我听见了一句长沙话,就想回长沙了。”逗霸妹听过很多人回长沙的…

git使用---工作区和暂存区

转载于:https://www.cnblogs.com/momo-unique/articles/4380551.html

偶数哥德巴赫猜想

已知不小于6的偶数都可以分成两个素数之和。请编写6到100000的所有偶数的分解&#xff0c;若有一个偶数可以分解成多个素数之和&#xff0c;只需写出一种即可。 #include <iostream> #include <algorithm> using namespace std;bool isprime(int n)//判断素数{int …

电脑常见故障处理_彩超常见故障及维修

彩超是医学检测手段中重要的环节之一&#xff0c;是对产妇以及对病人进行内部组织和结构观察的重要方式之一&#xff0c;彩超应用得当可以及早的诊断出病人的疾病&#xff0c;为患者解除疾病的困扰。彩超设备是一种极为先进的诊断系统&#xff0c;一般彩超系统包括以下几个部分…

用基本信号画出如下的信号_股市入门基本知识丨下跌时期可以抄底的安全信号有哪些...

点击蓝色字体 关注我们 带来更多精彩股票市场中的秘籍其实就是“低买高卖”&#xff0c;不过我们不能在大盘一开始下跌的时候就进行买入&#xff0c;因为不清楚下跌的时间&#xff0c;太早介入&#xff0c;只有在反弹幅度超出我们介入的点的时候才可以进行高卖。那么什么时候才…

Flume数据传输事务分析[转]

本文基于ThriftSource,MemoryChannel,HdfsSink三个组件&#xff0c;对Flume数据传输的事务进行分析&#xff0c;如果使用的是其他组件&#xff0c;Flume事务具体的处理方式将会不同。一般情况下&#xff0c;用MemoryChannel就好了&#xff0c;我们公司用的就是这个&#xff0c;…

yii2中的rules验证规则

2019独角兽企业重金招聘Python工程师标准>>> Rules验证规则&#xff1a;required : 必须值验证属性||CRequiredValidator 的别名, 确保了特性不为空.[[字段名],required,requiredValue>必填值,message>提示信息];email : 邮箱验证||CEmailValidator 的别名,确…

opengl 如何加阴影_动漫嘴唇厚涂如何绘制?厚涂嘴唇正确画法

动漫嘴唇厚涂如何绘制&#xff1f;厚涂嘴唇正确画法&#xff01;嘴巴怎么画&#xff1f;画嘴巴真的很考验一个画师功力&#xff0c;好看的嘴巴生动而丰满&#xff0c;可以给整幅画作添上亮点&#xff0c;而画的不好的嘴巴呢&#xff0c;就容易把画面整体的风格打破。那么零基础…

详解JMeter函数和变量

详解JMeter函数和变量&#xff08;1&#xff09; JMeter函数可以被认为是某种特殊的变量&#xff0c;它们可以被采样器或者其他测试元件所引用。函数调用的语法如下&#xff1a; ${__functionName(var1,var2,var3)} 其中&#xff0c;__functionName匹配被调用的函数名称。用圆括…

hdu 5199 map或二分或哈希

题目描述&#xff1a;给出n棵树的高度&#xff0c;每棵树上都站着一只鸟&#xff0c;枪手Jack站在最左边那棵树的左边对鸟进行射击&#xff0c;当Jack在高度为H的地方向右发射一颗子弹的时候&#xff0c;高度为H的树上的鸟儿就会掉落&#xff08;注&#xff1a;其他树上的鸟儿不…

数字电路实验怎么接线视频讲解_家庭影院中音箱、功放、投影机、4K播放机不知道怎么连接?手把手教你...

家庭影院中音箱、功放、投影机、4K播放机不知道怎么连接&#xff1f;手把手教你有不少用户收到从家庭影院器材之后&#xff0c;表示完全不会连接。翻看说明书也觉得头大&#xff0c;知识太多&#xff0c;然而却很难找到要点。今天主要跟大家讲讲如何连接音箱、功放、投影机和影…

.NET开发过程中的全文索引使用技巧之Solr

前言&#xff1a;相信许多人都听说过.net开发过程中基于Lucene.net实现的全文索引&#xff0c;而Solr是一个高性能&#xff0c;基于Lucene的全文搜索服务器。同时对其进行了扩展&#xff0c;提供了比Lucene更为丰富的查询语言&#xff0c;同时实现了可配置、可扩展并对查询性能…

auto.js停止所有线程_Java线程与并发编程实践:深入理解volatile和final变量

同步有两种属性&#xff1a;互斥性和可见性。synchronized关键字与两者都有关系。Java同时也提供了一种更弱的、仅仅包含可见性的同步形式&#xff0c;并且只以volatile关键字关联。假设你自己设计了一个停止线程的机制(因为无法使用Thread不安全的stop()方法))。清单1中Thread…

项目实例改编:利用structs2的action 实时显示图片、pdf和其他内容的框架抽取。(转)...

转自&#xff1a;http://www.verydemo.com/demo_c167_i1382.html 针对&#xff1a;预览文件&#xff08;图片&#xff0c;PDF&#xff09;文件来源为action中的inputStream 重点&#xff1a; structs2的action的配置 action的写法和结果类型 resulttype的写法 网页上实…