Advertisement
moonlightcheese

Untitled

Aug 17th, 2011
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 21.16 KB | None | 0 0
  1. package com.moonlightcheese.btsrv;
  2.  
  3. import java.lang.*;
  4. import java.lang.reflect.*;
  5. import java.io.*;
  6. import java.util.*;
  7.  
  8. import android.app.*;
  9. import android.os.*;
  10. import android.bluetooth.*;
  11. import android.content.*;
  12. import android.util.Log;
  13.  
  14. //service that dies when completely unbound
  15. public class ScannerService extends Service
  16. {
  17.     //debugging
  18.     private static final String LOG_TAG = "ScannerService";
  19.     private static final boolean D = true;
  20.    
  21.     // Member fields
  22.     public static final UUID BLUETOOTH_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");      //the UUID.  magic.
  23.     private final BluetoothAdapter mAdapter;
  24.     private BluetoothDevice mDevice;
  25.     private SharedPreferences mPrefs;
  26.     private NotificationManager mNM;
  27.     private AcceptThread mAcceptThread;
  28.     private ConnectThread mConnectThread;
  29.     private ConnectedThread mConnectedThread;
  30.     private int mState;
  31.    
  32.     // valid states
  33.     public static final String ACTION_START_SERVICE = "com.conceptualsystems.scannerservice.action.START_SERVICE";
  34.     public static final String ACTION_STATE_CHANGED = "com.conceptualsystems.scannerservice.action.STATE_CHANGED";
  35.         public static final String EXTRA_STATE = "com.conceptualsystems.scannerservice.extra.STATE";
  36.     public static final String ACTION_SELECT_SCANNER = "com.conceptualsystems.scannerservice.action.SELECT_SCANNER";
  37.         public static final String EXTRA_SELECTED_SCANNER = "com.conceptualsystems.scannerservice.extra.SELECTED_SCANNER";
  38.     public static final String ACTION_READ_SCANNER = "com.conceptualsystems.scannerservice.action.READ_SCANNER";
  39.     public static final String ACTION_REQUEST_RECONNECT = "com.conceptualsystems.scannerservice.action.REQUEST_RECONNECT";
  40.     public static final String ACTION_RECONNECT = "com.conceptualsystems.scannerservice.action.RECONNECT";
  41.     public static final String ACTION_RESET = "com.conceptualsystems.scannerservice.action.RESET";
  42.     public static final String ACTION_REQUEST_STATE = "com.conceptualsystems.scannerservice.action.REQUEST_STATE";
  43.    
  44.     // Constants representing various notifications of this service
  45.     public static final int NOTIFICATION_CONNECTION_CHANGED = 0;
  46.    
  47.     // Name for the SDP record when creating server socket
  48.     private static final String NAME = "ScannerService";
  49.  
  50.     // Constants that indicate the current connection state
  51.     public static final int STATE_NONE = 0;       // we're doing nothing
  52.     public static final int STATE_LISTEN = 1;     // now listening for incoming connections
  53.     public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
  54.     public static final int STATE_CONNECTED = 3;  // now connected to a remote device
  55.    
  56.     // Broadcast intent actions
  57.     //public static final String
  58.    
  59.     //instance of the Binder we define in this Service
  60.     private final IBinder mBinder = new ScannerBinder();
  61.    
  62.     // Class that extends Binder
  63.     ////////////////////////////
  64.     public class ScannerBinder extends Binder {
  65.         ScannerService getService () {
  66.             //return this instance
  67.             return ScannerService.this;
  68.         }
  69.     }
  70.    
  71.     @Override
  72.     public IBinder onBind(Intent intent) {
  73.         return mBinder;
  74.     }
  75.    
  76.     /**
  77.      * Constructor. Prepares a new BluetoothChat session.
  78.      * @param context  The UI Activity Context
  79.      * @param handler  A Handler to send messages back to the UI Activity
  80.      */
  81.     public ScannerService() {
  82.         mAdapter = BluetoothAdapter.getDefaultAdapter();
  83.         //mState = STATE_NONE;
  84.         //this.setState(STATE_NONE);
  85.     }
  86.    
  87.     @Override
  88.     public void onCreate() {
  89.         this.setState(STATE_NONE);
  90.        
  91.         mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  92.        
  93.         // If the adapter is null, then Bluetooth is not supported
  94.         showNotification("Service Started");
  95.        
  96.         mPrefs = getSharedPreferences("csccontrolcenterprefs", Context.MODE_PRIVATE);
  97.        
  98.         IntentFilter filter = new IntentFilter();
  99.         filter.addAction(ScannerService.ACTION_STATE_CHANGED);
  100.         filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  101.         filter.addAction(ScannerService.ACTION_SELECT_SCANNER);
  102.         filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
  103.         filter.addAction(ScannerService.ACTION_RESET);
  104.         filter.addAction(ScannerService.ACTION_REQUEST_STATE);
  105.         registerReceiver(mReceiver, filter);
  106.        
  107.         if (mAdapter == null) {
  108.             // TODO: find a way to make the application exit here.
  109.             // there is no reason to run this at all if there is no bluetooth adapter.
  110.             //return;
  111.             if(D) Log.e(LOG_TAG, "BAD THINGS HAPPENED: bluetooth adapter is null, so this device either doesn't have bluetooth, or the powers that be simply don't like you.");
  112.         }
  113.        
  114.         // If BT is not on, request that it be enabled.
  115.         // setupChat() will then be called during onActivityResult
  116.         if (!mAdapter.isEnabled()) {
  117.             mAdapter.enable();
  118.         // Otherwise, setup the chat session
  119.         } else {
  120.             //bluetooth is already enabled, so start connection attempt
  121.             this.start();
  122.         }
  123.     }
  124.    
  125.     @Override
  126.     public void onDestroy() {
  127.         super.onDestroy();
  128.         unregisterReceiver(mReceiver);
  129.         mNM.cancel(NOTIFICATION_CONNECTION_CHANGED);
  130.     }
  131.    
  132.     /**
  133.      * Set the current state of the chat connection
  134.      * @param state  An integer defining the current connection state
  135.      */
  136.     private synchronized void setState(int state) {
  137.         if (D) Log.d(LOG_TAG, "setState() " + mState + " -> " + state);
  138.         mState = state;
  139.        
  140.         Intent i = new Intent(ScannerService.ACTION_STATE_CHANGED);
  141.         i.putExtra(ScannerService.EXTRA_STATE, mState);
  142.         sendBroadcast(i);
  143.     }
  144.  
  145.     /**
  146.      * Return the current connection state.
  147.      */
  148.     public synchronized int getState() {
  149.         return mState;
  150.     }
  151.    
  152.     private void showNotification(String tickerText) {
  153.         Notification notification = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());
  154.         Intent selectionIntent = new Intent(this, SelectActivity.class);
  155.         selectionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  156.         PendingIntent contentIntent = PendingIntent.getActivity(this, 0, selectionIntent, 0); //this is how we will launch an Activity when the user clicks the notification
  157.         notification.setLatestEventInfo(this, getText(R.string.app_name), tickerText, contentIntent);
  158.         notification.flags|=Notification.FLAG_ONGOING_EVENT;
  159.         mNM.notify(NOTIFICATION_CONNECTION_CHANGED, notification);  //send the notification to the system, to be displayed in the notification bar
  160.     }
  161.    
  162.     // Create a BroadcastReceiver for ACTION_FOUND, ACTION_STATE_CHANGED, ACTION_DISCOVERY_FINISHED
  163.     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  164.         public void onReceive(Context context, Intent intent) {
  165.             String action = intent.getAction();
  166.             if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
  167.                 int state = mAdapter.getState();
  168.                 if(BluetoothAdapter.STATE_ON == state) {
  169.                     //bluetooth has been enabled.  attempt to connect to a scanner now.
  170.                     ScannerService.this.stop();     //clear out the connection threads
  171.                     ScannerService.this.start();    //reinitialize
  172.                 }
  173.                 if(BluetoothAdapter.STATE_OFF == state) {
  174.                     //
  175.                     ScannerService.this.start();
  176.                 }
  177.             }
  178.             if(ScannerService.ACTION_REQUEST_STATE.equals(action)) {
  179.                 Intent i = new Intent(ScannerService.ACTION_STATE_CHANGED);
  180.                 i.putExtra(ScannerService.EXTRA_STATE, getState());
  181.                 context.sendBroadcast(i);
  182.             }
  183.             if(ScannerService.ACTION_SELECT_SCANNER.equals(action)) {
  184.                 String macAddress = intent.getStringExtra(ScannerService.EXTRA_SELECTED_SCANNER);
  185.                
  186.                 if(D) Log.i(LOG_TAG, "got scanner selection: "+macAddress);
  187.                
  188.                 SharedPreferences.Editor edit = mPrefs.edit();
  189.                 edit.putString("scanner", macAddress);
  190.                 edit.commit();
  191.                 ScannerService.this.start();
  192.             }
  193.             if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
  194.                 //ScannerService.this.start();
  195.             }
  196.             if(ScannerService.ACTION_RESET.equals(action)) {
  197.                 Log.i(LOG_TAG, "reset request received");
  198.                 if(mAdapter.isEnabled()) {
  199.                     //ScannerService.this.stop();
  200.                     //ScannerService.this.start();
  201.                     mAdapter.disable();
  202.                 } else {
  203.                     ScannerService.this.start();
  204.                 }
  205.             }
  206.         }
  207.     };
  208.    
  209.     /**
  210.      * Start the chat service. Specifically start AcceptThread to begin a
  211.      * session in listening (server) mode. Called by the Activity onResume() */
  212.     public synchronized void start() {
  213.         if (D) Log.d(LOG_TAG, "start");
  214.        
  215.         if (!mAdapter.isEnabled()) {
  216.             mAdapter.enable();
  217.             return;
  218.         }
  219.        
  220.         // Cancel any thread attempting to make a connection
  221.         if (mState == STATE_CONNECTING) {
  222.             if (mConnectThread != null) {
  223.                 //mConnectThread.cancel();  //this fails because the Thread dies after connection, but is not null.  we can't call .cancel() if the Thread isn't running.
  224.                 mConnectThread = null;
  225.             }
  226.         }
  227.        
  228.         // Cancel any thread currently running a connection
  229.         if (mConnectedThread != null) {
  230.             mConnectedThread.cancel();  //this doesn't fail only because we know that if the Thread exists, it is looping and running.  this seems like bad coding, but don't know how to fix it.  was part of the Android example.
  231.             mConnectedThread = null;
  232.         }
  233.        
  234.         /*** OLD GARBAGE FROM BTCHATEXAMPLE ***
  235.         // Start the thread to listen on a BluetoothServerSocket
  236.         if (mAcceptThread == null) {
  237.             mAcceptThread = new AcceptThread();
  238.             mAcceptThread.start();
  239.         }
  240.         */
  241.         //setState(STATE_LISTEN);
  242.        
  243.         //check if we have set a preference for our scanner
  244.         //if not, display the selection dialog.
  245.         if(mPrefs!=null && mPrefs.contains("scanner")) {
  246.             try {
  247.                 mDevice = mAdapter.getRemoteDevice(mPrefs.getString("scanner", null));
  248.             } catch(Exception e) {
  249.                 if(D) Log.e(LOG_TAG, "i dunno how in the world you did it, but somehow you stored a null MAC address when selecting a scanner");
  250.             }
  251.             if(mDevice!=null) {
  252.                 this.connect(mDevice);
  253.             } else {
  254.                 if(D) Log.e(LOG_TAG, "mDevice is somehow null, after calling getRemoteDevice");
  255.             }
  256.         } else {
  257.             //start the activity that allows the user to set the bluetooth scanner
  258.             if(D) Log.i(LOG_TAG, "either mPrefs was null (which is really bad) or you need to select a scanner (not so bad)");
  259.            
  260.             ////////////////////////////////////////////////////
  261.             // TODO: start the scanner selection activity here
  262.             ////////////////////////////////////////////////////
  263.             Intent i = new Intent(ScannerService.this, SelectActivity.class);
  264.             i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  265.             startActivity(i);
  266.         }
  267.     }
  268.    
  269.     /**
  270.      * Stop all threads
  271.      */
  272.     public synchronized void stop() {
  273.         if (D) Log.d(LOG_TAG, "stop");
  274.         if (mConnectThread != null) {
  275.             //mConnectThread.cancel();
  276.             mConnectThread = null;
  277.         }
  278.         Log.i(LOG_TAG, "ended connect thread");
  279.         if (mConnectedThread != null) {
  280.             mConnectedThread.cancel();
  281.             mConnectedThread = null;
  282.         }
  283.         Log.i(LOG_TAG, "ended connected thread");
  284.         if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
  285.         setState(STATE_NONE);
  286.     }
  287.    
  288.     public synchronized void nullify(Thread t) {
  289.         t=null;
  290.     }
  291.    
  292.     /**
  293.      * Start the ConnectThread to initiate a connection to a remote device.
  294.      * @param device  The BluetoothDevice to connect
  295.      */
  296.     public synchronized void connect(BluetoothDevice device) {
  297.         if (D) Log.d(LOG_TAG, "connect to: " + device);
  298.        
  299.         // Cancel any thread attempting to make a connection
  300.         if (mState == STATE_CONNECTING) {
  301.             if (mConnectThread != null) {
  302.                 //mConnectThread.cancel();  //this should actually work without a hitch, solving the problem presented in the comments above in start()
  303.                 mConnectThread = null;
  304.             }
  305.         }
  306.        
  307.         // Cancel any thread currently running a connection
  308.         if (mConnectedThread != null) {
  309.             mConnectedThread.cancel();
  310.             mConnectedThread = null;
  311.         }
  312.        
  313.         // Start the thread to connect with the given device
  314.         mConnectThread = new ConnectThread(device);
  315.         mConnectThread.start();
  316.         setState(STATE_CONNECTING);
  317.     }
  318.    
  319.     /**
  320.      * Start the ConnectedThread to begin managing a Bluetooth connection
  321.      * @param socket  The BluetoothSocket on which the connection was made
  322.      * @param device  The BluetoothDevice that has been connected
  323.      */
  324.     public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
  325.         if (D) Log.d(LOG_TAG, "connected");
  326.        
  327.         // Cancel any thread currently running a connection
  328.         if (mConnectedThread != null) {
  329.             mConnectedThread.cancel();
  330.             mConnectedThread = null;
  331.         }
  332.        
  333.         // Start the thread to manage the connection and perform transmissions
  334.         mConnectedThread = new ConnectedThread(socket);
  335.         mConnectedThread.start();
  336.        
  337.         // Cancel the accept thread because we only want to connect to one device
  338.         if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
  339.        
  340.         // Cancel the thread that completed the connection
  341.         if (mConnectThread != null) {
  342.             //mConnectThread.cancel();
  343.             mConnectThread = null;
  344.         }
  345.        
  346.         // update the notification bar and let the user know we are connected.
  347.         showNotification("Scanner Connected");
  348.        
  349.         // Send the name of the connected device back to the UI Activity
  350.         // TODO: there is nothing to change here.  we don't care what the name is once we're connected.
  351.         //       just leave this commented.
  352.         /***
  353.         Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
  354.         Bundle bundle = new Bundle();
  355.         bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
  356.         msg.setData(bundle);
  357.         mHandler.sendMessage(msg);
  358.         ***/
  359.        
  360.         setState(STATE_CONNECTED);
  361.     }
  362.    
  363.     /**
  364.     * Indicate that the connection attempt failed and notify the UI Activity.
  365.     */
  366.     private void connectionFailed() {
  367.         setState(STATE_NONE);
  368.        
  369.         // Send a failure message to notification bar
  370.         showNotification("Scanner Disconnected");
  371.        
  372.         Log.e(LOG_TAG, "connectionFailed()");
  373.        
  374.         ///////DEPRECATED: we now inform the user that the connection failed and prompt them to try again.
  375.         // after we send a failure message, automatically attempt to reconnect
  376.         //this.start();
  377.        
  378.         //Intent intentError = new Intent(ScannerService.this, ErrorActivity.class);
  379.         //intentError.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  380.         //startActivity(intentError);
  381.        
  382.         /***
  383.         Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
  384.         Bundle bundle = new Bundle();
  385.         bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
  386.         msg.setData(bundle);
  387.         mHandler.sendMessage(msg);
  388.         ***/
  389.     }
  390.  
  391.     /**
  392.      * Indicate that the connection was lost and notify the UI Activity.
  393.      */
  394.     private void connectionLost() {
  395.         setState(STATE_NONE);
  396.        
  397.         // Send a failure message to notification bar
  398.         showNotification("Scanner Disconnected");
  399.        
  400.         Log.e(LOG_TAG, "connectionLost()");
  401.        
  402.         ///////DEPRECATED: we now inform the user that the connection failed and prompt them to try again.
  403.         // after we send a failure message, automatically attempt to reconnect
  404.         //this.start();
  405.        
  406.         //Intent intentError = new Intent(ScannerService.this, ErrorActivity.class);
  407.         //intentError.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  408.         //startActivity(intentError);
  409.        
  410.         /**
  411.         Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
  412.         Bundle bundle = new Bundle();
  413.         bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
  414.         msg.setData(bundle);
  415.         mHandler.sendMessage(msg);
  416.         **/
  417.     }
  418.    
  419.     /**
  420.      * This thread runs while listening for incoming connections. It behaves
  421.      * like a server-side client. It runs until a connection is accepted
  422.      * (or until cancelled).
  423.      */
  424.     private class AcceptThread extends Thread {
  425.         // The local server socket
  426.         private final BluetoothServerSocket mmServerSocket;
  427.        
  428.         public AcceptThread() {
  429.             BluetoothServerSocket tmp = null;
  430.            
  431.             // Create a new listening server socket
  432.             try {
  433.                 tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, BLUETOOTH_UUID);
  434.             } catch (IOException e) {
  435.                 Log.e(LOG_TAG, "listen() failed", e);
  436.                 mAdapter.disable();
  437.             }
  438.             mmServerSocket = tmp;
  439.         }
  440.        
  441.         public void run() {
  442.             if (D) Log.d(LOG_TAG, "BEGIN mAcceptThread" + this);
  443.             setName("AcceptThread");
  444.             BluetoothSocket socket = null;
  445.            
  446.             // Listen to the server socket if we're not connected
  447.             while (mState != STATE_CONNECTED) {
  448.                 try {
  449.                     // This is a blocking call and will only return on a
  450.                     // successful connection or an exception
  451.                     socket = mmServerSocket.accept();
  452.                 } catch (IOException e) {
  453.                     Log.e(LOG_TAG, "accept() failed", e);
  454.                     break;
  455.                 }
  456.                
  457.                 // If a connection was accepted
  458.                 if (socket != null) {
  459.                     synchronized (ScannerService.this) {
  460.                         switch (mState) {
  461.                         case STATE_LISTEN:
  462.                         case STATE_CONNECTING:
  463.                             // Situation normal. Start the connected thread.
  464.                             connected(socket, socket.getRemoteDevice());
  465.                             break;
  466.                         case STATE_NONE:
  467.                         case STATE_CONNECTED:
  468.                             // Either not ready or already connected. Terminate new socket.
  469.                             try {
  470.                                 socket.close();
  471.                             } catch (IOException e) {
  472.                                 Log.e(LOG_TAG, "Could not close unwanted socket", e);
  473.                             }
  474.                             break;
  475.                         }
  476.                     }
  477.                 }
  478.             }
  479.             if (D) Log.i(LOG_TAG, "END mAcceptThread");
  480.         }
  481.        
  482.         public void cancel() {
  483.             if (D) Log.d(LOG_TAG, "cancel " + this);
  484.             try {
  485.                 mmServerSocket.close();
  486.             } catch (IOException e) {
  487.                 Log.e(LOG_TAG, "close() of server failed", e);
  488.             }
  489.         }
  490.     }
  491.  
  492.  
  493.     /**
  494.      * This thread runs while attempting to make an outgoing connection
  495.      * with a device. It runs straight through; the connection either
  496.      * succeeds or fails.
  497.      */
  498.     private class ConnectThread extends Thread {
  499.         private final BluetoothSocket mmSocket;
  500.         private final BluetoothDevice mmDevice;
  501.        
  502.         public ConnectThread(BluetoothDevice device) {
  503.             mmDevice = device;
  504.             BluetoothSocket tmp = null;
  505.            
  506.             // Get a BluetoothSocket for a connection with the
  507.             // given BluetoothDevice
  508.             try {
  509.                 //tmp = device.createRfcommSocketToServiceRecord(BLUETOOTH_UUID);
  510.                 Method m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
  511.                 tmp = (BluetoothSocket)m.invoke(device, Integer.valueOf(1));
  512.             } catch (Exception e) {
  513.                 Log.e(LOG_TAG, "create() failed", e);
  514.                 connectionFailed();
  515.                 /*
  516.                 if(mAdapter.isEnabled()) {
  517.                     mAdapter.disable();
  518.                 } else {
  519.                     ScannerService.this.start();
  520.                 }
  521.                 */
  522.             }
  523.             mmSocket = tmp;
  524.         }
  525.        
  526.         public void run() {
  527.             if(mmSocket!=null) {
  528.                 Log.i(LOG_TAG, "BEGIN mConnectThread");
  529.                 setName("ConnectThread");
  530.                
  531.                 // Always cancel discovery because it will slow down a connection
  532.                 mAdapter.cancelDiscovery();
  533.                
  534.                 // Make a connection to the BluetoothSocket
  535.                 try {
  536.                     // This is a blocking call and will only return on a
  537.                     // successful connection or an exception
  538.                     mmSocket.connect();
  539.                 } catch (IOException e) {
  540.                     Log.e(LOG_TAG, "unable to connect() socket IOEXCEPTION", e);
  541.                     connectionFailed();
  542.                     // Close the socket
  543.                     try {
  544.                         mmSocket.close();
  545.                     } catch (IOException e2) {
  546.                         Log.e(LOG_TAG, "unable to close() socket during connection failure", e2);
  547.                     }
  548.                     return;
  549.                 } catch (NullPointerException e1) {
  550.                     Log.e(LOG_TAG, "unable to connect() socket NULLPOINTEREXCEPTION", e1);
  551.                     mAdapter.disable();
  552.                     return;
  553.                 }
  554.                
  555.                 // Reset the ConnectThread because we're done
  556.                 //synchronized (ScannerService.this) {
  557.                 //  mConnectThread = null;
  558.                 //}
  559.                
  560.                 // Start the connected thread
  561.                 if(mmSocket!=null && mmDevice!=null) {
  562.                     connected(mmSocket, mmDevice);
  563.                 }
  564.                
  565.                 try {
  566.                     Thread.sleep(1000);
  567.                 } catch(Exception e) {
  568.                     Log.e(LOG_TAG, "couldn't wait, sorry brofus");
  569.                 }
  570.             }
  571.         }
  572.        
  573.         public void cancel() {
  574.             try {
  575.                 mmSocket.close();
  576.             } catch (IOException e) {
  577.                 Log.e(LOG_TAG, "close() of connect socket failed", e);
  578.             } catch (NullPointerException e1) {
  579.                 Log.e(LOG_TAG, "unable to close() socket NULLPOINTEREXCEPTION", e1);
  580.             }
  581.         }
  582.     }
  583.  
  584.     /**
  585.      * This thread runs during a connection with a remote device.
  586.      * It handles all incoming and outgoing transmissions.
  587.      */
  588.     private class ConnectedThread extends Thread {
  589.         private final BluetoothSocket mmSocket;
  590.         private final LineNumberReader mmInStream;
  591.         private final OutputStream mmOutStream;
  592.        
  593.         public ConnectedThread(BluetoothSocket socket) {
  594.             Log.d(LOG_TAG, "create ConnectedThread");
  595.             mmSocket = socket;
  596.             LineNumberReader tmpIn = null;
  597.             OutputStream tmpOut = null;
  598.            
  599.             // Get the BluetoothSocket input and output streams
  600.             try {
  601.                 tmpIn = new LineNumberReader(new InputStreamReader(socket.getInputStream()));
  602.                 tmpOut = socket.getOutputStream();
  603.             } catch (IOException e) {
  604.                 Log.e(LOG_TAG, "temp sockets not created", e);
  605.             }
  606.            
  607.             mmInStream = tmpIn;
  608.             mmOutStream = tmpOut;
  609.         }
  610.        
  611.         public void run() {
  612.             Log.i(LOG_TAG, "BEGIN mConnectedThread");
  613.            
  614.             while(true) {
  615.                 try {
  616.                     String curScan = mmInStream.readLine();
  617.                     if (D) Log.i(LOG_TAG, "scan read in service: "+curScan);
  618.                    
  619.                     //////////////////////////////////////////////
  620.                     //TODO: send the read intent from here
  621.                     //////////////////////////////////////////////
  622.                     Intent i = new Intent(ScannerService.ACTION_READ_SCANNER);
  623.                     i.putExtra("scannerRead", curScan);
  624.                     sendBroadcast(i);
  625.                    
  626.                 } catch(IOException e) {
  627.                     connectionLost();
  628.                     break;
  629.                 }
  630.             }
  631.         }
  632.        
  633.         public void cancel() {
  634.             try {
  635.                 mmSocket.close();
  636.             } catch (IOException e) {
  637.                 Log.e(LOG_TAG, "close() of connect socket failed", e);
  638.             }
  639.         }
  640.     }
  641. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement