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.pswp.cn/news/259158.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/259158.shtml
英文地址,請注明出處:http://en.pswp.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…

除BUG記

我負責一個模塊,功能比較簡單,就是測量環境溫、濕度,外加控制空調開/關、溫度設定。就是這么幾個功能,就反復試驗、修改,才達到穩定。在調試時,出現各種各樣的BUG,一些是編程時候出現的語法錯誤…

正則表達式語法(轉)

正則表達式是一種文本模式,包括普通字符(例如,a 到 z 之間的字母)和特殊字符(稱為“元字符”)。模式描述在搜索文本時要匹配的一個或多個字符串。 正則表達式示例 表達式匹配 /^\s*$/ 匹配空行。 /\d{2}-…

迎戰校招訓練題

一、雙空 編譯器可以根據硬件特性選擇合適的類型長度,但要遵循如下限制:short與int類型至少為___C___位,long至少為__D____位,并且short類型不長于int類型,int類型不得長于long類型。 A. 4 B.8 C.16 D. 32 E. 64…

【ASP.NET Web API2】初識Web API

Web Api 是什么? MSDN:ASP.NET Web API 是一種框架,用于輕松構建可以訪問多種客戶端(包括瀏覽器和移動設備)的 HTTP 服務 百度百科:Web API是網絡應用程序接口。 個人理解:Web API 是提供給多種…

三星s8怎么分屏操作_三星手機該怎么玩?了解完這幾點用機技巧,可以輕車熟路了!...

其實對于三星這個手機品牌,我還是很佩服的。雖然近些年來,三星在國內的市場份額日漸變少,但是在國內的影響力依然尚存。畢竟三星手機在某些方面還是很有優勢的,特別是旗艦系列機型深受消費者喜愛。接下來,筆者就跟大家…

關于條件編譯的問題

這兩天來忙活ucos-II在PIC18fxxx系列上的移植。在編譯的時候老出現變量被多重定義的錯誤。花費了一天的功夫才成功編譯通過,錯誤何在??就是因為沒有搞明白條件編譯的原理,二是對mcc18編譯器的特點無知。下面學習條件編譯方面的知識…

二維數組的指針復習

最近一次的考試都是指針,真是給我深深上了一課,所以我特此復習一下指針方面的知識。二維數組的指針 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

UC/OS-II的學習

粗略的的看了邵貝貝老師的那本書,感覺有點眉目。UC/OS-II的全局變量繁多,剛接觸的時候容易弄混淆,現在總結下: OSRunning: 用于標識多任務環境是否已經開啟運行,在OSStart()函數里啟動任務后就置為True。 …

偶數哥德巴赫猜想

已知不小于6的偶數都可以分成兩個素數之和。請編寫6到100000的所有偶數的分解&#xff0c;若有一個偶數可以分解成多個素數之和&#xff0c;只需寫出一種即可。 #include <iostream> #include <algorithm> using namespace std;bool isprime(int n)//判斷素數{int …

[20170420]表達式加0或者減0不一樣.txt

[20170420]表達式加0或者減0不一樣.txt --//oracle 有時候避免某個索引采用字段0或者-0的方式&#xff0c;不使用索引&#xff0c;但是兩者存在一點點區別&#xff0c;通過例子說明。 1.環境&#xff1a; SCOTTbook> &r/ver1 PORT_STRING VERSION …

MAPLAP開發環境中release模式和debug模式燒寫.hex文件的不同之處

昨天看了齊工的報告才知道release模式和debug模式燒寫.hex文件的不同。 三&#xff1a;問題分析 1. PIC系列的仿真器和集成開發環境的情況&#xff1a; Release模式和Debug模式是有區別的&#xff1b;Release模式是只把代碼燒錄到單片機的flash區內&#xff0c;上電執行&am…

JavaWeb -- Session實例 -- 自動登錄 和 防止表單重復提交(令牌產生器) MD5碼

1、 自動登錄 http://blog.csdn.net/xj626852095/article/details/16825659 2. 防止表單重復提交 表單Servlet //負責產生表單 public class FormServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletEx…

電腦常見故障處理_彩超常見故障及維修

彩超是醫學檢測手段中重要的環節之一&#xff0c;是對產婦以及對病人進行內部組織和結構觀察的重要方式之一&#xff0c;彩超應用得當可以及早的診斷出病人的疾病&#xff0c;為患者解除疾病的困擾。彩超設備是一種極為先進的診斷系統&#xff0c;一般彩超系統包括以下幾個部分…

微軟歷史最高市值是多少?

有人說微軟在1999 年 12 月達到股價歷史最高點 $58.38并不準確。我1999年12月22日增加微軟&#xff0c;公司依照1999年12月27日的價格&#xff08;119.125&#xff0c;拆股后變為59.5625&#xff09;給了我一筆期權&#xff0c;這個價格&#xff0c;成為微軟股價空前絕后最高點…

京東2016校招編程題

記得有一個大題&#xff0c;說的是給定一個n*n的矩陣&#xff0c;要求從1開始填充矩陣&#xff0c;最后的矩陣是蛇形的。即如下&#xff1a; n3, 7 8 1 6 9 2 5 4 3 n4, 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4 給出代碼&#xff1a; #incl…