连接线程建立失败

时间:2016-04-01 17:42:14

标签: java android android-bluetooth

当我尝试通过从配对设备列表中选择蓝牙设备来建立连接时,应用程序崩溃并返回主要活动。

PairingList.java

 public class PairingList extends Activity implements AdapterView.OnItemClickListener {
        private static final int SUCCESS_CONNECT = 0;
        private static final int MESSAGE_READ = 1;
        ListView lview;
        String[] paires;
        ArrayAdapter<String> adapter;
        Set<BluetoothDevice> devicesarray;
        BluetoothAdapter mBluetoothAdapter;
        ArrayList<BluetoothDevice> devices;
        public BluetoothSocket socket;
        public final UUID MY_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
        Handler mHandler = new Handler(){
            @Override
             public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    switch (msg.what){
                        case SUCCESS_CONNECT:
                            ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket) msg.obj);
                            String s="Successfully Connected";
                            connectedThread.write(s.getBytes());
                            break;
                        case MESSAGE_READ:
                            byte[] readBuf=(byte[])msg.obj;
                            String s1=new String(readBuf);
                            Toast.makeText(getBaseContext(),"Connect",Toast.LENGTH_SHORT).show();
                        }
                }
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.pairinglist_layout);
            lview= (ListView) findViewById(R.id.listviewid);
            mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
            Bundle bn1=getIntent().getExtras();
            paires=bn1.getStringArray("paires");
            adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,paires);
            lview.setAdapter(adapter);
            lview.setOnItemClickListener(this);
            devices=new ArrayList<BluetoothDevice>();

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_pairinglist_layout, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            BluetoothDevice selectedDevice=devices.get(position);
            ConnectThread connect=new ConnectThread(selectedDevice);
            connect.start();
        }
        private class ConnectThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;

            public ConnectThread(BluetoothDevice device) {
                // Use a temporary object that is later assigned to mmSocket,because mmSocket is final
                BluetoothSocket tmp = null;
                mmDevice = device;

                // Get a BluetoothSocket to connect with the given BluetoothDevice
                try {
                    // MY_UUID is the app's UUID string, also used by the server code
                    tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) { }
                mmSocket = tmp;
            }

            public void run() {
                mBluetoothAdapter.cancelDiscovery();   // Cancel discovery because it will slow down the connection

                try {
                    // Connect the device through the socket. This will block until it succeeds or throws an exception
                    mmSocket.connect();
                } catch (IOException connectException) {
                    // Unable to connect; close the socket and get out
                    try {
                        mmSocket.close();
                    } catch (IOException closeException) { }
                    return;
                }

                // Do work to manage the connection (in a separate thread)
                mHandler.obtainMessage(SUCCESS_CONNECT,mmSocket).sendToTarget();
            }



            /** Will cancel an in-progress connection, and close the socket */
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) { }
            }
        }
        private class ConnectedThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;

            public ConnectedThread(BluetoothSocket socket) {
                mmSocket = socket;
                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                // Get the input and output streams, using temp objects because
                // member streams are final
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) { }

                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }

            public void run() {
                byte[] buffer ;  // buffer store for the stream
                int bytes; // bytes returned from read()

                // Keep listening to the InputStream until an exception occurs
                while (true) {
                    try {
                        // Read from the InputStream
                        buffer= new byte[1024];
                        bytes = mmInStream.read(buffer);
                        // Send the obtained bytes to the UI activity
                        mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                                .sendToTarget();
                    } catch (IOException e) {
                        break;
                    }
                }
            }

            /* Call this from the main activity to send data to the remote device */
            public void write(byte[] bytes) {
                try {
                    mmOutStream.write(bytes);
                } catch (IOException e) { }
            }

            /* Call this from the main activity to shutdown the connection */
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) { }
            }
        }
    }

调用此方法时,应用程序崩溃:

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    BluetoothDevice selectedDevice=devices.get(position);
    ConnectThread connect=new ConnectThread(selectedDevice);
    connect.start();
}

我甚至试图在其中放入一个祝酒词,但它没有被执行。

0 个答案:

没有答案