I am trying to connect two phones without pairing it using createInsecureRfcommSocketToServiceRecord
method unable to connect device and it throws IOException. System.err: java.io.IOException: socket closed
You can see my code . In App there is new scanning bluetooth devices list when i click on that particular item its goes to second Activity and it connect with that device.
Code :
This OnItemClick is listner of Searched new devices list.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bdDevice = arrayListBluetoothDevices.get(position);
Intent intents = new Intent(Main_Activity.this, SecondActivity.class);
intents.putExtra("deviceAddress", bdDevice.getAddress());
startActivity(intents);
}
SecondActivity.class :
@Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
address = intent.getStringExtra("deviceAddress");
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
try {
//I am creating insecureRFcomm because of no pairing dialog required.
socket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
socket.getRemoteDevice().getAddress();
} catch (Exception e) {
e.printStackTrace();
}
bluetoothAdapter.cancelDiscovery();
Log.d(TAG, "...Connecting to Remote...");
try {
//Connection establish between BT-Device and phone.
socket.connect();
counter = 0;
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
//Connection close.
socket.close();
if (inStream!=null){
inStream.close();
}
} catch (Exception e2) {
e.printStackTrace();
e2.printStackTrace();
}
finally {
final AlertDialog alertDialog = new AlertDialog.Builder(SBLActivity.this).create();
alertDialog.setMessage("Device is Non SBL.");
alertDialog.setTitle("Device Connection");
alertDialog.setCancelable(false);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.show();
}
}
}
I am getting error at Socket.connect();
and it goes to catch block. How to fix that, OR any other way to connect bluetooth socket without pairing dialog or Paring device or with pairng device and no pairing dialog
Thank you.