Advertisement
moonlightcheese

service dead wtf

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