蓝牙设备在Android中没有第二次连接

时间:2015-03-04 13:47:56

标签: java android sockets bluetooth

我的Android应用程序将蓝牙设备连接为客户端。

第一次尝试: 设备连接,关闭应用程序,套接字和iostreams关闭。

第二次尝试: 设备没有连接,但我得到连接的吐司。没有例外。

关闭蓝牙设备然后再打开,使设备连接并且问题仍然存在

public class ConnectingThread extends Thread{


private ImageView connect;
private Context context; 

private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

private BluetoothAdapter mmAdapter;
public static  BluetoothSocket mmSocket ;
private  InputStream mmInStream ;
private   OutputStream mmOutStream ;
private  VibrotacDevice device;


public ConnectingThread(BluetoothDevice device, Context context,  BluetoothAdapter adapter ) {

    mmAdapter=adapter;
     // connect=(ImageView) ((Activity)context).findViewById(R.id.connectionimg);
    this.context=context;
    BluetoothSocket tmp = null;


    // 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);
         Log.d("Mainbt", "inside constructor try");
    } catch (IOException e) {

        Log.d("Mainbt", "inside constructor catch: "+ e.getMessage());
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    mmSocket = tmp;

}

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

    try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception
        mmSocket.connect();
        Log.d("Mainbt", "connecting");
    } catch (final IOException connectException) {
        // Unable to connect; close the socket and get out

        ((Activity) context).runOnUiThread(new Runnable() {

            @Override
            public void run() {   
                Log.d("Mainbt", " unable to connect"+ connectException.getMessage());
                Toast.makeText(context, connectException.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });  


        try {
            mmSocket.close();
            Log.d("Mainbt", " trying to close connection0");
            ((Activity) context).runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Log.d("Mainbt", " trying to close connection1");
                     //  connect.setImageResource(R.drawable.connectionstatus_disconnected); 
                    Toast.makeText(context, "Could not establish Connection", Toast.LENGTH_SHORT).show();
                }
            });  



        } catch (IOException closeException) {
        }
        return;
    }


         ((Activity) context).runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Log.d("Mainbt", "connected");
               // connect.setImageResource(R.drawable.connectionstatus_connected);
              Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();


        }
    });    



     connectingStreams();

 } 

public void connectingStreams( ){
    try {
         mmInStream = mmSocket.getInputStream();
         mmOutStream =mmSocket.getOutputStream();

        } catch (IOException e) {
    }



         try {
         connectedVibration();
    } catch (InterruptedException e) {

        e.printStackTrace();
    }  


}


public  void cancel() {

     if(mmInStream!=null){

         try {
             Log.d("Mainbt", "closingIstream");
            mmInStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         mmInStream=null;
         Log.d("Mainbt", "closedIstream");
     }
     if(mmOutStream!=null){

         try {
             Log.d("Mainbt", "closingOstream");
            mmOutStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         mmOutStream=null;
         Log.d("Mainbt", "closedOstream");
     }


        }

public static void cancelSocket(){

    if(mmSocket!=null){

         try {
             Log.d("Mainbt", "closingSocket");
             mmSocket.close();

         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }  
         Log.d("Mainbt", "closedSocket");
            mmSocket=null;
         }

  }

}

上述类是从Acticity调用的,它在一个对话框中显示设备名称和mac地址,单击它,启动一个连接

private void initializeBluetooth() {

      adapter=BluetoothAdapter.getDefaultAdapter();
    if(adapter==null){
        Toast.makeText(getApplicationContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();            
        finish();
    } else{

        //Checks if bluetooth is enabled
        if(adapter.isEnabled()){

        devices= new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice );
            Set<BluetoothDevice> pairedDevices=adapter.getBondedDevices();

            // checks if any device have been paired previously 
            if(pairedDevices.size()> 0){


                for(BluetoothDevice device: pairedDevices){
                    devices.add(device.getName()+"\n"+device.getAddress());

                    }

                showPairedDialog();
            }else{
                //Dialog to scan new devices
                showScanningDialog();
            }

            }else{

                Intent enablebt= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enablebt, REQUEST_ENABLE_BT);

        }


    }
}

private void showScanningDialog() {
    AlertDialog.Builder builder= new AlertDialog.Builder(this);
    builder.setTitle("No devices Paired");
    builder.setMessage("Would you like to scan for devices");

    builder.setNegativeButton("cancel", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();

        }
    });

    builder.setPositiveButton("Scan", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
             //devices.clear();

            Log.v("checkup", "inside onclick ");
            discoverDevice();
        }


    });
    builder.create();
    builder.show();
}

private void showPairedDialog() {
    AlertDialog.Builder builder= new AlertDialog.Builder(this); 

    builder.setTitle("Paired Devices");


    builder.setAdapter(devices, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int item) {
            Toast.makeText(getApplicationContext(), "Connecting to device...", Toast.LENGTH_SHORT).show();
            //connect.setImageResource(R.drawable.connectionstatus_connecting);
            String info= devices.getItem(item);
            String address= info.substring(info.length()-17);
            BluetoothDevice btDevice=adapter.getRemoteDevice(address);
            ct= new ConnectingThread( btDevice,context,adapter );
             ct.start();
        }
    });

    builder.setNeutralButton("cancel", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
             dialog.dismiss();
        }
    });

    builder.setPositiveButton("Scan", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "Scanning...", Toast.LENGTH_SHORT).show();
              devices.clear();


            discoverDevice();

        }
    });

    dialog= builder.create();
    dialog.show();

}

private void discoverDevice() {
     Log.v("checkup", "inside discover ");
     adapter.startDiscovery();
      receiver= new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();             


            if (BluetoothDevice.ACTION_FOUND.equals(action)) {            
                // Get the BluetoothDevice object from the Intent  

                BluetoothDevice bluedevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);            

                    if(bluedevice.getBondState()!=BluetoothDevice.BOND_BONDED){
                // Add the name and address to an array adapter to show in a ListView            
                devices.add(bluedevice.getName() + "\n" + bluedevice.getAddress());  
                Toast.makeText(getApplicationContext(),bluedevice.getName() , Toast.LENGTH_SHORT).show();
                 }    
            }


            }
    };

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(receiver, filter); 

    AlertDialog.Builder builder= new AlertDialog.Builder(this);
        builder.setAdapter(devices, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int item) {

                Toast.makeText(getApplicationContext(), "Connecting to device...", Toast.LENGTH_SHORT).show();

                String info= devices.getItem(item);
                String address= info.substring(info.length()-17);
                BluetoothDevice btDevice=adapter.getRemoteDevice(address);
                  ct= new ConnectingThread( btDevice,context,adapter);
                 ct.start();

            }
        });

        builder.setNegativeButton("cancel", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
             dialog.dismiss();

            }
        });

        builder.create();
        builder.show();

    }

@Override
 protected void onActivityResult(int requestCode, int resultCode,Intent data){

     if(requestCode==REQUEST_ENABLE_BT && resultCode==RESULT_OK){

         initializeBluetooth();
     } 

}

请帮帮我

0 个答案:

没有答案