Skip to content

Instantly share code, notes, and snippets.

@sidishere
Created December 24, 2019 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidishere/6087a410fcf535556d15a203c072faa8 to your computer and use it in GitHub Desktop.
Save sidishere/6087a410fcf535556d15a203c072faa8 to your computer and use it in GitHub Desktop.
private class ConnectBT extends AsyncTask<Void, Void, Void>
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(LedControl.this, "Connecting...", "Please wait!!!");  //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
Log.i("APP","Trying "+btSocket.toString());
btSocket.connect();//start connection
Log.i("APP","After Trying "+btSocket.toString());
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
Log.i("APP","Connection failed "+e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
Toast.makeText(getApplicationContext(),"Connection Failed. Is it a SPP Bluetooth? Try again.",Toast.LENGTH_SHORT).show();
Log.i("APP","Conn status"+ConnectSuccess);
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Connected.",Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
progress.dismiss();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment