0

Till now my app can discover make discoverable and all these.When i press the device's name for example of my near cellphone(which i have opened the bluetooth) it appears in my listview fact that i want.After when i press it ,i have the classic error << "W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1 ">>.It doesnt work the bluetoothSocket.connect in my code. In other case when i go into my car with my tablet(which includes my app from android studio) i can search the obd2 and when i press it ,it makes the bond requirement.I am keying in the 1234 password and make the bond in tablets bluetooth features where i can see it.I need someone who have did something like this to help me to the next steps.for example how to send a command for rpm or speed and take response.Please help me!

Here is my code:

public class BluetoothActivity extends AppCompatActivity {

private static final String TAG ="msg" ;
private BluetoothAdapter bluetoothAdapter;
private ToggleButton toggleButton;
private ListView listview;
private ArrayAdapter adapter;
private static final int MESSAGE_READ =1;
private static final int ENABLE_BT_REQUEST_CODE = 1;
private static final int DISCOVERABLE_BT_REQUEST_CODE = 2;
private static final int DISCOVERABLE_DURATION = 300;
private final static UUID uuid = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");

// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // Whenever a remote Bluetooth device is found
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            adapter.add(bluetoothDevice.getName() + "\n"
                    + bluetoothDevice.getAddress());
            adapter.notifyDataSetChanged();
        }
        //uuid=BluetoothDevice.getUuids()[0].getUuid();
    }
};

// IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

// registerReceiver(broadcastReceiver, filter) // Don't forget to unregister during onDestroy

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);

    toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

    listview = (ListView) findViewById(R.id.listView);


    //Listview Item Click Listener
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String itemValue = (String) listview.getItemAtPosition(position);
            String MAC = itemValue.substring(itemValue.length() - 17);
            BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC);
            // Initiate a connection request in a separate thread
            ConnectingThread t = new ConnectingThread(bluetoothDevice);
            t.start();
        }
    });

    adapter = new ArrayAdapter
            (this, android.R.layout.simple_list_item_1);
    listview.setAdapter(adapter);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

}

//Οταν πατάμε το button για να ανοίξει το bluetooth!
public void onToggleClicked(View view) {

    adapter.clear();

    ToggleButton toggleButton = (ToggleButton) view;
    if (bluetoothAdapter == null) {
        // Device does not support Bluetooth
        Toast.makeText(getApplicationContext(), "Η συσκευή δεν υποστηρίζει bluetooth.",
                Toast.LENGTH_SHORT).show();
        toggleButton.setChecked(false);
    } else {

        if (toggleButton.isChecked()){ // to turn on bluetooth
            if (!bluetoothAdapter.isEnabled()) {
                // A dialog will appear requesting user permission to enable Bluetooth
                Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetoothIntent, ENABLE_BT_REQUEST_CODE);
            } else {
                Toast.makeText(getApplicationContext(), "Η Συσκευή είναι έτοιμη για χρήση." +
                                "\n" + "Ανίχνευση για Απομακρυσμένες Συσκευές...",
                        Toast.LENGTH_SHORT).show();
                // To discover remote Bluetooth devices
                discoverDevices();
                // Make local device discoverable by other devices
                makeDiscoverable();
            }
        } else { // Turn off bluetooth

            bluetoothAdapter.disable();
            adapter.clear();
            Toast.makeText(getApplicationContext(), "Η συσκευή έχει Απενεργοποιηθεί.",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == ENABLE_BT_REQUEST_CODE) {

        // Bluetooth successfully enabled!
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(getApplicationContext(), "Το Bluetooth έχει Ενεργοποιηθεί." +
                            "\n" + "Ανίχνευση για Απομακρυσμένες Συσκευές...",
                    Toast.LENGTH_SHORT).show();

            // To discover remote Bluetooth devices
            discoverDevices();

            // Make local device discoverable by other devices
            makeDiscoverable();
              // Start a thread to create a  server socket to listen
            // for connection request
            ListeningThread t = new ListeningThread();
            t.start();


        } else { // RESULT_CANCELED as user refused or failed to enable Bluetooth
            Toast.makeText(getApplicationContext(), "Το Bluetooth δεν έχει Ενεργοποιηθεί.",
                    Toast.LENGTH_SHORT).show();

            // Turn off togglebutton
            toggleButton.setChecked(false);
        }
    } else if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){

        if (resultCode == DISCOVERABLE_DURATION){
            Toast.makeText(getApplicationContext(), "Η συσκευή είναι τώρα Ανιχνεύσιμη απο άλλες συσκευές..  " +
                            DISCOVERABLE_DURATION + " Δευτερόλεπτα",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Αποτυχία να Ενεργοποιηθεί η Ανιχνευσημότητα της Συσκευής.",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

protected void discoverDevices(){
    // To scan for remote Bluetooth devices
    if (bluetoothAdapter.startDiscovery()) {
        Toast.makeText(getApplicationContext(), "Ανίχνευση για άλλες Συσκευές Bluetooth...",
                Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getApplicationContext(), "Η Ανίχνευση Απέτυχε να αρχίσει.",
                Toast.LENGTH_SHORT).show();
    }
}
 //Συνάρτηση για makeDiscoverable
protected void makeDiscoverable(){
    // Make local device discoverable
    Intent discoverableIntent = new
            Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
    startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}

@Override
protected void onResume() {
    super.onResume();
    // Register the BroadcastReceiver for ACTION_FOUND
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(broadcastReceiver, filter);
}
 //on pause an xreiastei na bei kwdikas{}
 @Override
 protected void onPause() {
     super.onPause();
     this.unregisterReceiver(broadcastReceiver);
 }
@Override
     public boolean onCreateOptionsMenu(Menu menu) {
             // Inflate the menu; this adds items to the action bar if it is present.
             getMenuInflater().inflate(R.menu.bluetooth, menu);
             return true;
          }
@Override
 public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

//Thread gia ton server..
private class ListeningThread extends Thread {
    private final BluetoothServerSocket bluetoothServerSocket;
   //Constructor
    public ListeningThread() {
        BluetoothServerSocket temp = null;
        try {
            temp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid);

        } catch (IOException e) {
            e.printStackTrace();
        }
        bluetoothServerSocket = temp;
    }

    public void run() {
        BluetoothSocket bluetoothSocket = null;
        // This will block while listening until a BluetoothSocket is returned
        // or an exception occurs
        Log.d(TAG, "O kwdikas edw trexei");
        while (true) {
            try {
                bluetoothSocket = bluetoothServerSocket.accept();
            } catch (IOException e) {
                break;
            }

            // If a connection is accepted
            if (bluetoothSocket != null) {
                //!!!!!!!!!!!!!!!!
                 runOnUiThread(new Runnable() {
                 public void run() {
                Toast.makeText(getApplicationContext(), "Επιτυχής Σύνδεση με την συσκευή.",
                        Toast.LENGTH_SHORT).show();
                  }

                });
                 ConnectedThread  a = new ConnectedThread(bluetoothSocket);
                  a.start();
                try {
                    bluetoothServerSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;

            }
        }
    }

    public void cancel() {
        try {
            bluetoothServerSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

    private class ConnectingThread extends Thread{
        private final BluetoothSocket bluetoothSocket;
        private final BluetoothDevice bluetoothDevice ;

        public ConnectingThread(BluetoothDevice device){
            BluetoothSocket temp = null;
            bluetoothDevice = device;
            //Get a BluetoothSocket to connect with the given BluetoothDevice
            try{

       temp=bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);

            }catch (IOException e){
                e.printStackTrace();
            }
            bluetoothSocket = temp;

            }


        public void run() {

            // Cancel discovery as it will slow down the connection
            bluetoothAdapter.cancelDiscovery();
            try {

                bluetoothSocket.connect();
                Log.d(TAG, "the code is running");
                // This will block until it succeeds in connecting to the device
                // through the bluetoothSocket or throws an exception
              //  bluetoothSocket.connect();
                //isConnected = true;
            } catch (IOException connectException) {
                connectException.printStackTrace();
                try {
                    //unable to connect

                    bluetoothSocket.close();
                } catch (IOException closeException) {
                    closeException.printStackTrace();
                }
            }
            // Do work to manage the connection (in a separate thread)
            //manageConnectedSocket(bluetoothSocket);
            ConnectedThread  t= new ConnectedThread(bluetoothSocket);
            t.start();

        }



    // Cancel an open connection and terminate the thread
    public void cancel() {
        try {
            bluetoothSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
private class ConnectedThread extends Thread {


    private final BluetoothSocket bluetoothSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    private android.os.Handler mHandler;

    public ConnectedThread(BluetoothSocket socket) {
        bluetoothSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity

                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
    }

    // Call this from the main activity to send data to the remote device
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    // Call this from the main activity to shutdown the connection
    public void cancel() {
        try {
            bluetoothSocket.close();
            mmInStream.close();
            mmOutStream.close();
        } catch (IOException e) { }
    }

    public void setmHandler(Handler mHandler) {
        this.mHandler = mHandler;
    }
}

}

dionysis
  • 1
  • 1
  • 2

1 Answers1

1

You have been able to pair the OBDII adapter that is plugged into the diagnostic port on a vehicle with your phone, but now you need to connect to it.

Connect to the device with:

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    BluetoothDevice device = btAdapter.getRemoteDevice(deviceAddress);

    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);

    socket.connect();

Once you are connected to the device you can initialize the OBDII adapter with AT commands, such as "AT E0" for echo off, and "AT L0" for line-feed off.

You can then continuously get data from the vehicle by issuing the corresponding PID codes: for RPM use "01 0C", for speed use "01 0D".

More detail and discussion can be found at this link:

http://blog.lemberg.co.uk/how-guide-obdii-reader-app-development

Here is a link to a good OBD2 starter library that you can extend and improve for your specialized needs:

https://github.com/pires/obd-java-api

Bob_in_NJ
  • 11
  • 4