Hello, Elton. I wonder if you're still active, but I need help. So here is the problem. I'm able to pair with my ELM327, but somehow can't keep the connection established after I enter the code (1234). Here's my code:
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ACCESS_FINE_LOCATION = 2;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
private ListView listview;
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> listAdapter;
private List<String> device_name = new ArrayList<>();
private List<String> device_address = new ArrayList<>();
private BluetoothSocket cnt_socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we get bluetooth adapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listview = findViewById(R.id.listview);
// we create a simple array adapter to display devices detected
listAdapter = new ArrayAdapter<>(this, R.layout.list_style);
listview.setAdapter(listAdapter);
// pairing
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
startThread(position);
}
});
// we check bluetooth state
checkBluetoothState();
// we start scanning
scan();
//we check permission a start of the app
checkCoarseLocationPermission();
checkFineLocationPermission();
}
public void scan() {
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
// we check if coarse location must be asked
if (checkCoarseLocationPermission()) {
listAdapter.clear();
device_name.clear();
device_address.clear();
bluetoothAdapter.startDiscovery();
}
} else {
checkBluetoothState();
}
}
public void startThread(int position) {
BluetoothConnect btConnect = new BluetoothConnect(position);
btConnect.start();
Toast.makeText(this, "Connecting ...", Toast.LENGTH_SHORT).show();
}
class BluetoothConnect extends Thread {
int position;
BluetoothConnect(int position) {
this.position = position;
}
@Override
public void run() {
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(device_address.get(position));
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothSocket socket = null;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.connect();
cnt_socket = socket;
} catch (IOException e) {
e.printStackTrace();
}
device.createBond();
}
}
@Override
protected void onResume() {
super.onResume();
// we register a dedicated receiver for some Bluetooth actions
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private boolean checkCoarseLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
} else {
return true;
}
}
private boolean checkFineLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ACCESS_FINE_LOCATION);
return false;
} else {
return true;
}
}
private void checkBluetoothState() {
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on your device!", Toast.LENGTH_SHORT).show();
} else {
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "You need to enable Bluetooth", Toast.LENGTH_SHORT).show();
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
checkBluetoothState();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_ACCESS_COARSE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Access coarse location allowed. You can scan Bluetooth devices", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Access coarse location forbidden. You can't scan Bluetooth devices", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
// we need to implement our receiver to get devices detected
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName() != null && !device_address.contains(device.getAddress())) {
listAdapter.add(device.getName() + "\n" + device.getAddress());
listAdapter.notifyDataSetChanged();
device_name.add(device.getName());
device_address.add(device.getAddress());
}
} else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
try {
new EchoOffCommand().run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
new LineFeedOffCommand().run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
new TimeoutCommand(125).run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
new SelectProtocolCommand(ObdProtocols.AUTO).run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
new AmbientAirTemperatureCommand().run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(context, "Showing device(s), please wait ...", Toast.LENGTH_LONG).show();
}
}
};