1. Download our Official Android App: Forums for Android!

Apps Detect Bluetooth disconnect from Scanner

Discussion in 'Android Development' started by Nedals, Oct 19, 2011.

  1. Nedals

    Nedals Lurker
    Thread Starter
    Rank:
    None
    Points:
    6
    Posts:
    3
    Joined:
    Oct 19, 2011

    Oct 19, 2011
    3
    1
    6
    Pleasanton, CA
    I have a small Android APP that connects the phone to a Scanner via Bluetooth. The APP connects and returns scan data as needed.
    However, I need to be able to detect, and notify the user, when the scanner goes out of range and then auto-reconnect,
    or have the user manually reconnect using a Dialog Box, when the Scanner is back in range.

    I tried inserting a Timer that tries to connect every 10secs or so which opens a Dialog box
    and stops the timer, but it did not work and it's real messy.

    I thought there must be a simple method to do this.

    Here is a truncated version of my current code
    Code (Text):
    1.  
    2. public class BluetoothListener {
    3.     private BluetoothSocket mmSocket;  //
    4.     ...
    5.     mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    6.     ...
    7.     private void connect() {
    8.         try {
    9.             mmSocket.connect();
    10.             mListener = new StartListener(); mListener.start();
    11.         }
    12.         catch (IOException e) {
    13.             try { mmSocket.close(); } catch (IOException ex) {}
    14.             // Currently creates a working [reconnect]/[close] Dialog
    15.             mHandler.obtainMessage(2, "Dialog Alert".getBytes()).sendToTarget();
    16.         }
    17.     }
    18.    
    19.     private class StartListener extends Thread {
    20.         private final InputStream mmInStream;
    21.         public StartListener() {
    22.             mState = LISTENING;
    23.             InputStream tmpIn = null;
    24.             try {
    25.                 tmpIn = mmSocket.getInputStream();
    26.             }
    27.             catch (IOException e) {}
    28.             mmInStream = tmpIn;
    29.         }
    30.        
    31.         public void run() {
    32.             try {
    33.                 InputStreamReader mReader = new InputStreamReader(mmInStream, "UTF-8");
    34.                 final BufferedReader bufferedReader = new BufferedReader(mReader);
    35.                 String line = "";
    36.                 while ((line=bufferedReader.readLine())!=null){
    37.                     mHandler.obtainMessage(1, line.getBytes()).sendToTarget();
    38.                 }
    39.             }
    40.             catch (Exception e) {}
    41.         }
    42.         ...
    43.     }
    44.     ...
    45. }
    46.  
     

    Advertisement

Share This Page

Loading...