11package eu .basicairdata .bluetoothhelper ;
22
3+
34/**
45 * BluetoothHelper Java Helper Class for Android
56 * Created by G.Capelli (BasicAirData) on 06/02/16.
4445* You can read the incoming messages attaching a Listener or using explicit polling.<br>
4546* Connection, reading and writing processes are asynchronously made using 3 separated Threads.<br>
4647* This Class is compatible with Android 4.0+
47- * @version 1.0.6b_20180526
48+ * @version 1.0.5
4849* @author BasicAirData
4950*/
5051
@@ -76,12 +77,12 @@ public ConnectThread(BluetoothDevice device) {
7677try {
7778tmp = (BluetoothSocket )m .invoke (mmDevice ,1 );
7879 }catch (IllegalAccessException e ) {
79- Log .w ("myApp" ,"[ ! ] Unable to connect socket (IllegalAccessException): " +e );
80+ // Log.w("myApp", "[! ] Unable to connect socket (IllegalAccessException): " + e);
8081 }catch (InvocationTargetException e ) {
81- Log .w ("myApp" ,"[ ! ] Unable to connect socket (InvocationTargetException): " +e );
82+ // Log.w("myApp", "[! ] Unable to connect socket (InvocationTargetException): " + e);
8283 }
8384 }catch (NoSuchMethodException e ) {
84- Log .w ("myApp" ,"[ ! ] Unable to connect socket (NoSuchMethodException): " +e );
85+ // Log.w("myApp", "[! ] Unable to connect socket (NoSuchMethodException): " + e);
8586 }
8687mmSocket =tmp ;
8788 }
@@ -92,33 +93,29 @@ public void run() {
9293try {
9394mmSocket .connect ();
9495 }catch (IOException connectException ) {
95- Log .w ("myApp" ,"[ ! ] Connection through socket failed: " +connectException );
96- Log .w ("myApp" ,"[ ! ] Trying fallback method" );
96+ // Log.w("myApp", "[! ] Connection through socket failed: " + connectException);
97+ // Log.w("myApp", "[! ] Trying fallback method");
9798try {
9899// fallback method for android >= 4.2
99100tmp = (BluetoothSocket )mmDevice .getClass ().getMethod ("createRfcommSocket" ,new Class []{int .class }).invoke (mmDevice ,1 );
100101 }catch (IllegalAccessException e ) {
101- Log .w ("myApp" ,"[ ! ] Failed to create fallback Illegal Access: " +e );
102+ // Log.w("myApp", "[! ] Failed to create fallback Illegal Access: " + e);
102103return ;
103104 }catch (IllegalArgumentException e ) {
104- Log .w ("myApp" ,"[ ! ] Failed to create fallback Illegal Argument: " +e );
105+ // Log.w("myApp", "[! ] Failed to create fallback Illegal Argument: " + e);
105106return ;
106107 }catch (InvocationTargetException e ) {
107- Log .w ("myApp" ,"[ ! ] Failed to create fallback Invocation Target" +e );
108+ // Log.w("myApp", "[! ] Failed to create fallback Invocation Target" + e);
108109return ;
109110 }catch (NoSuchMethodException e ) {
110- Log .w ("myApp" ,"[ ! ] Failed to create fallback No Such Method" +e );
111+ // Log.w("myApp", "[! ] Failed to create fallback No Such Method" + e);
111112return ;
112113 }
113114try {
114115// linked to tmp, so basicly a new socket
115116mmSocket .connect ();
116117 }catch (IOException e ) {
117- Log .w ("myApp" ,"[ ! ] Failed to connect with fallback socket: " +e );
118- try {
119- sleep (200 );
120- }catch (InterruptedException ex ) {
121- }
118+ //Log.w("myApp", "[!] Failed to connect with fallback socket: " + e);
122119handler .post (new Runnable () {
123120@ Override
124121public void run () {
@@ -127,11 +124,11 @@ public void run() {
127124 });
128125return ;
129126 }
130- Log .w ("myApp" ,"[ # ] Succesfully connected with fallback socket" );
127+ // Log.w("myApp", "[# ] Succesfully connected with fallback socket");
131128 }
132129// Do work to manage the connection (in a separate thread)
133130// manageConnectedSocket(mmSocket);
134- Log .w ("myApp" ,"[ # ] Socket connected. Opening streams...." );
131+ // Log.w("myApp", "[# ] Socket connected. Opening streams....");
135132readThread =new ConnectedThreadClass_Read (mmSocket );
136133readThread .start ();
137134writeThread =new ConnectedThreadClass_Write (mmSocket );
@@ -144,7 +141,7 @@ public void run() {
144141try {
145142sleep (100 );
146143 }catch (InterruptedException e ) {
147- Log .w ("myApp" ,"[ ! ] ConnectThread Interrupted" );
144+ // Log.w("myApp", "[! ] ConnectThread Interrupted");
148145break ;
149146 }
150147// check the status of the connection and send listeners in case of changes
@@ -160,7 +157,7 @@ public void run() {
160157 }while (isConnected ());
161158cancel ();
162159//checkConnectionStatus();
163- Log .w ("myApp" ,"[ # ] Socket closed" );
160+ // Log.w("myApp", "[# ] Socket closed");
164161 }
165162
166163//Will cancel an connection and close streams and socket
@@ -180,8 +177,8 @@ public void cancel() {
180177
181178private void InCaseFireonBluetoothHelperConnectionStateChanged () {
182179if (listener !=null ) {
183- if (isConnected ())Log .w ("myApp" ,"[ # ] Listener fired: onBluetoothHelperConnectionStateChanged = true" );
184- else Log .w ("myApp" ,"[ # ] Listener fired: onBluetoothHelperConnectionStateChanged = false" );
180+ if (isConnected ())Log .w ("myApp" ,"[# ] Listener fired: onBluetoothHelperConnectionStateChanged = true" );
181+ else Log .w ("myApp" ,"[# ] Listener fired: onBluetoothHelperConnectionStateChanged = false" );
185182listener .onBluetoothHelperConnectionStateChanged (this ,isConnected ());// <---- fire listener
186183 }
187184 }
@@ -206,7 +203,7 @@ public ConnectedThreadClass_Read(BluetoothSocket socket) {
206203 }
207204
208205public void run () {
209- Log .w ("myApp" ,"[ # ] Input Stream opened" );
206+ // Log.w("myApp", "[# ] Input Stream opened");
210207// Keep listening to the InputStream until an exception occurs
211208while (true ) {
212209byte []buffer =new byte [1024 ];// buffer store for the stream
@@ -226,24 +223,24 @@ public void run() {
226223 }
227224 }
228225isInStreamConnected =false ;
229- Log .w ("myApp" ,"[ # ] Input stream closed" );
226+ // Log.w("myApp", "[# ] Input stream closed");
230227 }
231228 }
232229
233230// Service function: Message received!
234231private void MessageReceived (String msg ) {
235232// if the listener is attached fire it
236233// else put the message into buffer to be read
237- Log .w ("myApp" ,"[ # ] Message received: " +msg );
234+ // Log.w("myApp", "[# ] Message received: " + msg);
238235try {
239236if (listener !=null ) {
240- Log .w ("myApp" ,"[ # ] Listener fired: onBluetoothHelperMessageReceived" );
237+ // Log.w("myApp", "[# ] Listener fired: onBluetoothHelperMessageReceived");
241238listener .onBluetoothHelperMessageReceived (this ,msg );// <---- fire listener
242239 }else if (!inputMessagesQueue .offer (msg ))
243- Log .w ("myApp" ,"[ ! ] Message thrown (unable to store into buffer): " +msg )
240+ // Log.w("myApp", "[! ] Message thrown (unable to store into buffer): " + msg)
244241 ;
245242 }catch (Exception e ) {
246- Log .w ("myApp" ,"[ ! ] Failed to receive message: " +e .getMessage ());
243+ // Log.w("myApp", "[! ] Failed to receive message: " + e.getMessage());
247244 }
248245 }
249246
@@ -267,29 +264,29 @@ public ConnectedThreadClass_Write(BluetoothSocket socket) {
267264 }
268265
269266public void run () {
270- Log .w ("myApp" ,"[ # ] Output Stream opened" );
267+ // Log.w("myApp", "[# ] Output Stream opened");
271268// Keep sending messages to OutputStream until an exception occurs
272269while (true ) {
273270String msg ;
274271try {
275272msg =outputMessagesQueue .take ();
276273 }catch (InterruptedException e ) {
277274isOutStreamConnected =false ;
278- Log .w ("myApp" ,"[ ! ] Buffer not available: " +e .getMessage ());
275+ // Log.w("myApp", "[! ] Buffer not available: " + e.getMessage());
279276break ;
280277 }
281278try {
282279mmOutStream .write (msg .getBytes ());
283280mmOutStream .write (Delimiter );
284- Log .w ("myApp" ,"[ # ] Message send: " +msg );
281+ // Log.w("myApp", "[# ] Message send: " + msg);
285282 }catch (IOException e ) {
286283isOutStreamConnected =false ;
287- Log .w ("myApp" ,"[ ! ] Unable to write data to output stream: " +e .getMessage ());
284+ // Log.w("myApp", "[! ] Unable to write data to output stream: " + e.getMessage());
288285break ;
289286 }
290287 }
291288isOutStreamConnected =false ;
292- Log .w ("myApp" ,"[ # ] Output stream closed" );
289+ // Log.w("myApp", "[# ] Output stream closed");
293290 }
294291 }
295292
@@ -374,20 +371,20 @@ public boolean isConnected() {
374371* @see android.bluetooth.BluetoothDevice#getName()
375372*/
376373public void Connect (String DeviceName ) {
377- Log . w ( "myApp" , "[ # ] Connect(String DeviceName)" );
378- mBluetoothAdapter = BluetoothAdapter . getDefaultAdapter (); // Find adapter
379- if (( mBluetoothAdapter != null ) && (! DeviceName . isEmpty ())) {
380- if ( isConnected ()) Disconnect ( false );
374+ if (! isConnected ()) {
375+ Disconnect ( false );
376+
377+ mBluetoothAdapter = BluetoothAdapter . getDefaultAdapter (); // Find adapter
381378if (mBluetoothAdapter .isEnabled ()) {// Adapter found
382379Set <BluetoothDevice >devices =mBluetoothAdapter .getBondedDevices ();// Collect all bonded devices
383380for (BluetoothDevice bt :devices ) {
384381if (DeviceName .equals (bt .getName ())) {// Find requested device name
385- Log .w ("myApp" ,"[ # ] Devicename match found: " +bt .getName ());
386- Connect (bt );
387- }//else Log.w("myApp", "[ # ] Devicename doesn't match: " + bt.getName());
382+ //Log.w("myApp", "[#] Devicename match found: " + bt.getName());
383+ CT =new ConnectThread (bt );
384+ CT .start ();
385+ }//else Log.w("myApp", "[#] Devicename doesn't match: " + bt.getName());
388386 }
389387 }
390-
391388 }
392389 }
393390
@@ -407,10 +404,9 @@ public void Connect(String DeviceName) {
407404 * @see android.bluetooth.BluetoothDevice
408405 */
409406public void Connect (BluetoothDevice bluetoothDevice ) {
410- Log .w ("myApp" ,"[ # ] Connect(BluetoothDevice bluetoothDevice)" );
411- mBluetoothAdapter =BluetoothAdapter .getDefaultAdapter ();// Find adapter
412- if ((mBluetoothAdapter !=null ) && (bluetoothDevice !=null )) {
413- if (isConnected ())Disconnect (false );
407+ if (!isConnected ()) {
408+ Disconnect (false );
409+
414410mBluetoothAdapter =BluetoothAdapter .getDefaultAdapter ();// Find adapter
415411if (mBluetoothAdapter .isEnabled ()) {// Adapter found
416412CT =new ConnectThread (bluetoothDevice );
@@ -426,8 +422,8 @@ public void Connect(BluetoothDevice bluetoothDevice) {
426422* The method is public in case of particular user needs.
427423*/
428424public void ClearBuffer () {
429- if ( inputMessagesQueue != null ) inputMessagesQueue .clear ();// Clear the input message queue;
430- if ( outputMessagesQueue != null ) outputMessagesQueue .clear ();// Clear the output message queue;
425+ inputMessagesQueue .clear ();// Clear the input message queue;
426+ outputMessagesQueue .clear ();// Clear the output message queue;
431427 }
432428
433429
@@ -437,7 +433,10 @@ public void ClearBuffer() {
437433* An onBluetoothHelperConnectionStateChanged event occurs (if listener is attached) when the disconnection process terminates, returning the new status of the connection.
438434*/
439435public void Disconnect () {
440- Disconnect (true );
436+ if (CT !=null ) {
437+ if (CT .isAlive ())CT .cancel ();
438+ }
439+ ClearBuffer ();
441440 }
442441
443442
@@ -468,8 +467,6 @@ public void Disconnect(boolean ClearBuffer) {
468467* @return The String containing the message. An empty string otherwise
469468*/
470469public String ReceiveMessage () {
471- if (inputMessagesQueue !=null )return "" ;
472-
473470String m =inputMessagesQueue .poll ();
474471return (m !=null ?m :"" );
475472 }
@@ -483,7 +480,7 @@ public String ReceiveMessage() {
483480* @return true if the message is stored in the sending queue. false if a problem occurs
484481*/
485482public boolean SendMessage (String msg ) {
486- if (isConnected () && ( msg != null ) && ( outputMessagesQueue != null ) ) {
483+ if (isConnected ()) {
487484return (outputMessagesQueue .offer (msg ));
488485 }else return false ;
489486 }