Android bluetooth connection with an obd2 -


till app can discover make discoverable , these.when press device's name example of near cellphone(which have opened bluetooth) appears in listview fact want.after when press ,i have classic error << "w/bluetoothadapter: getbluetoothservice() called no bluetoothmanagercallback w/system.err: java.io.ioexception: read failed, socket might closed or timeout, read ret: -1 ">>.it doesnt work bluetoothsocket.connect in code. in other case when go car tablet(which includes app android studio) can search obd2 , when press ,it makes bond requirement.i keying in 1234 password , make bond in tablets bluetooth features can see it.i need have did me next steps.for example how send command rpm or speed , take response.please me!

here 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 broadcastreceiver action_found private final broadcastreceiver broadcastreceiver = new broadcastreceiver() {     public void onreceive(context context, intent intent) {         string action = intent.getaction();         // whenever remote bluetooth device found         if (bluetoothdevice.action_found.equals(action)) {             // bluetoothdevice object intent             bluetoothdevice bluetoothdevice = intent.getparcelableextra(bluetoothdevice.extra_device);             // add name , address array adapter show in 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 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 connection request in 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 not support bluetooth         toast.maketext(getapplicationcontext(), "Η συσκευή δεν υποστηρίζει bluetooth.",                 toast.length_short).show();         togglebutton.setchecked(false);     } else {          if (togglebutton.ischecked()){ // turn on bluetooth             if (!bluetoothadapter.isenabled()) {                 // dialog appear requesting user permission 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();                 // discover remote bluetooth devices                 discoverdevices();                 // make local device discoverable 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 enabled!         if (resultcode == activity.result_ok) {             toast.maketext(getapplicationcontext(), "Το bluetooth έχει Ενεργοποιηθεί." +                             "\n" + "Ανίχνευση για Απομακρυσμένες Συσκευές...",                     toast.length_short).show();              // discover remote bluetooth devices             discoverdevices();              // make local device discoverable other devices             makediscoverable();               // start thread create  server socket listen             // connection request             listeningthread t = new listeningthread();             t.start();           } else { // result_canceled user refused or failed 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(){     // scan 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 broadcastreceiver action_found     intentfilter filter = new intentfilter(bluetoothdevice.action_found);     this.registerreceiver(broadcastreceiver, filter); }  //on pause xreiastei na bei kwdikas{}  @override  protected void onpause() {      super.onpause();      this.unregisterreceiver(broadcastreceiver);  } @override      public boolean oncreateoptionsmenu(menu menu) {              // inflate menu; adds items action bar if present.              getmenuinflater().inflate(r.menu.bluetooth, menu);              return true;           } @override  public boolean onoptionsitemselected(menuitem item) {     // handle action bar item clicks here. action bar     // automatically handle clicks on home/up button, 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;         // block while listening until bluetoothsocket returned         // or exception occurs         log.d(tag, "o kwdikas edw trexei");         while (true) {             try {                 bluetoothsocket = bluetoothserversocket.accept();             } catch (ioexception e) {                 break;             }              // if connection accepted             if (bluetoothsocket != null) {                 //!!!!!!!!!!!!!!!!                  runonuithread(new runnable() {                  public void run() {                 toast.maketext(getapplicationcontext(), "Επιτυχής Σύνδεση με την συσκευή.",                         toast.length_short).show();                   }                  });                  connectedthread  = 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 bluetoothsocket connect given bluetoothdevice             try{         temp=bluetoothdevice.createinsecurerfcommsockettoservicerecord(uuid);              }catch (ioexception e){                 e.printstacktrace();             }             bluetoothsocket = temp;              }           public void run() {              // cancel discovery slow down connection             bluetoothadapter.canceldiscovery();             try {                  bluetoothsocket.connect();                 log.d(tag, "the code running");                 // block until succeeds in connecting device                 // through bluetoothsocket or throws exception               //  bluetoothsocket.connect();                 //isconnected = true;             } catch (ioexception connectexception) {                 connectexception.printstacktrace();                 try {                     //unable connect                      bluetoothsocket.close();                 } catch (ioexception closeexception) {                     closeexception.printstacktrace();                 }             }             // work manage connection (in separate thread)             //manageconnectedsocket(bluetoothsocket);             connectedthread  t= new connectedthread(bluetoothsocket);             t.start();          }        // cancel open connection , terminate 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;          // input , output streams, using temp objects because         // member streams 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 stream         int bytes; // bytes returned read()          // keep listening inputstream until exception occurs         while (true) {             try {                 // read inputstream                 bytes = mminstream.read(buffer);                 // send obtained bytes ui activity                  mhandler.obtainmessage(message_read, bytes, -1, buffer)                         .sendtotarget();             } catch (ioexception e) {                 break;             }     }      // call main activity send data remote device     public void write(byte[] bytes) {         try {             mmoutstream.write(bytes);         } catch (ioexception e) { }     }      // call main activity shutdown connection     public void cancel() {         try {             bluetoothsocket.close();             mminstream.close();             mmoutstream.close();         } catch (ioexception e) { }     }      public void setmhandler(handler mhandler) {         this.mhandler = mhandler;     } } 

}

you have been able pair obdii adapter plugged diagnostic port on vehicle phone, need connect it.

connect 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 connected device can initialize obdii adapter @ commands, such "at e0" echo off, , "at l0" line-feed off.

you can continuously data vehicle issuing corresponding pid codes: rpm use "01 0c", speed use "01 0d".

more detail , discussion can found @ link:

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

here link obd2 starter library can extend , improve specialized needs:

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


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -