Android:蓝牙插座拒绝正确连接

时间:2011-12-12 22:43:47

标签: android sockets bluetooth

我有一个蓝牙发射器试图连接到我写的基于BluetoothChat(android示例API)的服务。

一旦我运行命令mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID),蓝牙就会自动连接(在accept();命令之前,从而使接受阻止流程)。任何想法?

我的猜测是有一个套接字在之前的运行中没有正确关闭 - 尽管在这方面的调试没有显示出任何有趣的东西。

代码:

public class BluetoothService extends Service {


    // Unique UUID for this application
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");



    @Override
    public void onCreate() {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mAdapter == null) {
            Log.e(TAG, "Bluetooth is not available");
            stopSelf();
            return;
        }

        mState = STATE_NONE;
    }
    @Override
    public int onStartCommand(Intent BluetoothService, int flags, int startId ) {
        /**
        * Start the chat service. Specifically start AcceptThread to begin a
        * session in listening (server) mode. Called by the Activity onResume() */


        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to listen on a BluetoothServerSocket
        if (mAcceptThread == null) {
            mAcceptThread = new AcceptThread();
            mAcceptThread.start();
            }
        setState(STATE_LISTEN);
        return START_NOT_STICKY;
    }

    /**
     * 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 socket
         private BluetoothServerSocket mmServerSocket = null;

         public AcceptThread() 
         {
             BluetoothServerSocket tmp = null;

             // Create a new listening server socket
             try 
             {
                 //mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID);
                 tmp= mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID);
             } 
             catch (IOException e) 
             {
                 e.printStackTrace();
                 stopSelf();
             }              
             mmServerSocket = tmp;
         }

         public void run() {
              setName("AcceptThread");
              socket = null;
             // Listen to the server socket if we're not connected
             while (mState != STATE_CONNECTED) {
                 try {
                     // This is a blocking call and will only return on a
                     // successful connection or an exception
                     if (socket==null)
                         socket = mmServerSocket.accept();
                     } catch (IOException e) {
                         break;
                         }
                 // If a connection was accepted
                 if (socket != null) {
                     synchronized (BluetoothService.this) {
                         switch (mState) {
                             case STATE_LISTEN:
                             // Situation normal. Start the connected thread.
                             connected(socket, socket.getRemoteDevice());
                             break;
                             case STATE_NONE:
                             case STATE_CONNECTED:
                                 // Either not ready or already connected. Terminate new socket.
                                 try {
                                     socket.close();
                                     } catch (IOException e) {
                                     }
                                    break;
                                }
                            }
                        }
                  }
                  }

           public void cancel() 
           {
               try {
                   if(mmServerSocket!=null) mmServerSocket.close();
                   } catch (IOException e) {
                       Log.e(TAG, "close() of server failed", e);
                   }
           }
     }

        /**
        * Indicate that the connection was lost and notify the UI Activity.
        */
     private void connectionLost() {
         setState(STATE_LISTEN);
        // Start the service over to restart listening mode
            // Start the thread to listen on a BluetoothServerSocket
            if (mAcceptThread == null) {
                mAcceptThread = new AcceptThread();
                mAcceptThread.start();
                }
     }

     /**
      * This thread runs during a connection with a remote device.
      * It handles all incoming and outgoing transmissions.
      */
     private class ConnectedThread extends Thread {          
         public ConnectedThread(BluetoothSocket socket) {
             Log.d(TAG, "create ConnectedThread");
             InputStream tmpIn = null;
             OutputStream tmpOut = null;
             tabulkaBluetooth=socket.getRemoteDevice();
             tabulkaMac=tabulkaBluetooth.getAddress(); //MAC address of the tabulka to be used as ID at the server

             // We need an Editor object to make preference changes.
              // All objects are from android.context.Context

             // editor.commit();
             // Get the BluetoothSocket input and output streams
             try {
                 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");

                 int bytes;
             String coordinates = ""; //new coordinates from the tabulka
             String newCoordinates=null;
             byte[] buffer = new byte[1024];
             // Keep listening to the InputStream while connected
             int inputStreamAviableBool=0; //0- not aviable 1-aviable
             //---------diagnostic msg
             byte[] sendBuffer = new byte[3];
             sendBuffer[0] = 0x0a;
             sendBuffer[1] = 1;
             sendBuffer[2] = 'A';
             try {
                mmOutStream.write(sendBuffer);
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            //---------end of diagnostic msg 
             SystemClock.sleep(1000) ;
             int numOfInputReads=1;
             while(numOfInputReads<3)
             {
                 try {
                     inputStreamAviableBool=mmInStream.available();
                } catch (IOException e1) {
                     Log.e(TAG, "checking availability of inputStream IOException:", e1);
                }

                  while(inputStreamAviableBool!=0 ){
                        try{
                            bytes = mmInStream.read(buffer);
                            if(bytes == -1)
                                 Log.e(TAG, "input stream is over");
                        } catch (IOException e) {
                             Log.e(TAG, "reading from inputStream IOException:", e);
                        }
                        newCoordinates = new String(buffer);
                        coordinates=coordinates+newCoordinates;
                        try {
                            numOfInputReads++;
                            SystemClock.sleep(2000) ;
                            mmOutStream.write(sendBuffer);
                        } catch (IOException e2) {
                            // TODO Auto-generated catch block
                            e2.printStackTrace();
                        }
                        try {
                             inputStreamAviableBool=mmInStream.available();
                        } catch (IOException e1) {
                             Log.e(TAG, "checking availability of inputStream IOException:", e1);
                        }
                        if(inputStreamAviableBool>=3) inputStreamAviableBool=0;
                    }
                  numOfInputReads++;
                  SystemClock.sleep(2000) ;
             }

         disconnect();
         connectionLost();
         stopSelf();
         //-------end--------debuging 
         }  

         public void cancel() {
         try {
        //  if(mmSocket!=null) mmSocket.close();
             if(socket!=null) socket.close();
             } catch (IOException e) {
                     Log.e(TAG, "close() of connect socket failed", e);
                 }
         }

         private void disconnect() {
            Log.d(TAG, "closing");

            if (mmInStream != null) {
                try {
                    mmInStream.close();

                } catch (IOException e) {
                    Log.e(TAG, "isBt IOE", e);              
                }
                mmInStream = null;


            }

            if (mmOutStream != null) {
                try {
                    mmOutStream.close();

                } catch (IOException e) {
                    Log.e(TAG, "isBt IOE", e);              
                }
               mmOutStream = null;

            }

           if (socket != null) {
                try{
                   socket.close();
                    }
                   catch (IOException e) {
                        Log.e(TAG, "socket haven't been close", e);              
                    }
               socket = null;

            }
            Log.d(TAG, "closed");       
        }

     }

     /**
      * 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, BluetoothDevice device) {
         if (D) Log.d(TAG, "connected");
         // Cancel any thread currently running a connection
         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
         // Cancel the accept thread because we only want to connect to one device
         if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
         // Start the thread to manage the connection and perform transmissions
         mConnectedThread = new ConnectedThread(socket);
         mConnectedThread.start();


         setState(STATE_CONNECTED);
     }


}

0 个答案:

没有答案