6

My android app connects a Bluetooth device as a client.

1st try: The device gets connected and on closing the app, socket and iostreams gets closed.

2nd try: The device does not connect but I get the toast that says connected. No exceptions are encountered.

Turning the Bluetooth device Off and then on, makes the device to connect and problem persists

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;
         }

  }

}

The above class is called from an Acticity which displays the device name and mac address in a diaog box, clicking it, initiates a connection

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();
     } 

}

Please help me out here

user3763570
  • 157
  • 1
  • 9
  • How do you know you aren't getting any exceptions? Have you stepped through to make sure? It has to be failing somewhere. Then you have something like this `catch (IOException closeException) { }` – codeMagic Mar 04 '15 at 13:58
  • 1
    @codeMagic same problem here with exception `open java.io.IOException: read failed, socket might closed or timeout, read ret: -1` – Jorge B. Nov 26 '15 at 15:42
  • @JorgeB. sounds like your device is trying to communicate through the socket that's closed. Might need to close the socket on the device end. Also make sure it isn't trying to connect on a different thread. That's part of the problem I was having here http://stackoverflow.com/a/24919107/1380752 – codeMagic Nov 26 '15 at 15:54
  • @codeMagic my device end is a printer... – Jorge B. Nov 27 '15 at 11:00
  • @JorgeB. you'd need to post a question with relevant code and complete error message for help. Also explain what known platforms you are getting the exception with. Otherwise, it's impossible to know what you have going on – codeMagic Nov 27 '15 at 16:48

0 Answers0