Bluetooth Pairing rejects during attempt to programmatically connect BT in android -


i trying connect bluetooth device (bt headphone) programmatically android app. issue facing in first couple of attempts fails connect device , says "pairing rejected". after connects successfully.

here's code:

package rockwellcollins.bluetooth_pairing_siu;  import android.bluetooth.bluetootha2dp; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothprofile; import android.bluetooth.bluetoothsocket; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.bundle; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.util.log; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.toast;  import java.io.bufferedreader; import java.io.bufferedwriter; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.io.printwriter; import java.lang.reflect.invocationtargetexception; import java.lang.reflect.method; import java.net.inetaddress; import java.net.serversocket; import java.net.socket; import java.util.uuid;  public class mainactivity extends appcompatactivity {      public serversocket serversocket;     public bluetootha2dp bta2dp;     bluetoothadapter mbluetoothadapter;     private bluetoothsocket msocket = null;     private uuid applicationuuid = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb");     public inetaddress serveraddr,serveraddrconnected;     public socket socket,socketconnected;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);         toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar);         setsupportactionbar(toolbar);          floatingactionbutton fab = (floatingactionbutton) findviewbyid(r.id.fab);         fab.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view view) {                 snackbar.make(view, "replace own action", snackbar.length_long)                         .setaction("action", null).show();             }         });          mbluetoothadapter   = bluetoothadapter.getdefaultadapter();         mbluetoothadapter.getprofileproxy(this, new bluetoothprofile.servicelistener() {             @override             public void onserviceconnected(int profile, bluetoothprofile proxy) {                 log.i("oncreate","bluetooth service connected.\n");                 bta2dp = (bluetootha2dp) proxy;             }              @override             public void onservicedisconnected(int profile) {                 log.i("oncreate", "bluetooth service disconnected.\n");             }         }, bluetoothprofile.a2dp);          log.i("oncreate", "going start thread.\n");         thread fst = new thread(new serverthread());         fst.start();         registerreceiver(mpairreceiver, new intentfilter(bluetoothdevice.action_bond_state_changed));     }      public class serverthread implements runnable     {         string[] strline;         @override         public void run() {             try {                 mbluetoothadapter = bluetoothadapter.getdefaultadapter();                 serversocket = new serversocket(4500);                 while(true) {                     log.i("inrun","in run method");                     socket client = serversocket.accept();                     bufferedreader in = new bufferedreader(new inputstreamreader(client.getinputstream()));                     string line = in.readline();                      strline = line.split(";");                     log.i("serverthread", "line is: " + strline[1]);                     bluetoothdevice device = mbluetoothadapter.getremotedevice(strline[1]);                     if(strline[0].contains("connect")) {                         pairdevice(device);                     }                     else if(strline[0].contains("unpair"))                     {                         log.i("run","going unpair device");                         unpairdevice(device, strline[2]);                      }                 }             } catch (exception e) {                 e.printstacktrace();             }         }     }      public void pairdevice(bluetoothdevice device) {          try {             if(device.getbondstate() == bluetoothdevice.bond_none) {                 method method = device.getclass().getmethod("createbond", (class[]) null);                 method.invoke(device, (object[]) null);                 log.d("pairdevice", string.valueof(device.getbondstate()));             }          } catch (exception e) {             e.printstacktrace();         }     }      public class finalthread implements runnable{          string strmsg = "";         public finalthread(string msg)         {             strmsg = msg;         }         @override         public void run() {             try {                  serveraddr = inetaddress.getbyname("10.240.8.23");                 socket = new socket(serveraddr,5500);                  printwriter out = new printwriter(new bufferedwriter(new outputstreamwriter(socket.getoutputstream())), true);                 out.println(strmsg);                 out.flush();                 socket.close();              } catch (exception e) {                 e.printstacktrace();             }         }     }      private void unpairdevice(bluetoothdevice device, string seatinfo) {         try {             if(device.getbondstate() == bluetoothdevice.bond_bonded) {                 method method = device.getclass().getmethod("removebond", (class[]) null);                 method.invoke(device, (object[]) null);             }             thread sthread = new thread(new connectthread(seatinfo));             sthread.start();         } catch (exception e) {             e.printstacktrace();         }     }      public class connectthread implements runnable{         string strseat = "";         public connectthread(string seat){             strseat = seat;         }         @override         public void run() {             try {                  log.i("connectthread","going connect");                 serveraddr = inetaddress.getbyname("10.240.8.23");                 socket = new socket(serveraddr,5500);                  printwriter out = new printwriter(new bufferedwriter(new outputstreamwriter(socket.getoutputstream())), true);                 out.println("startpairconnect;" + strseat);                 out.flush();                 socket.close();                 log.i("connectthread","send message connect");              } catch (exception e) {                 e.printstacktrace();             }         }     }      private final broadcastreceiver mpairreceiver = new broadcastreceiver() {         public void onreceive(context context, intent intent) {             string action = intent.getaction();             bluetoothdevice devicebt = intent.getparcelableextra(bluetoothdevice.extra_device);             if (bluetoothdevice.action_bond_state_changed.equals(action)) {                 final int state         = intent.getintextra(bluetoothdevice.extra_bond_state, bluetoothdevice.error);                 final int prevstate = intent.getintextra(bluetoothdevice.extra_previous_bond_state, bluetoothdevice.error);                  if (state == bluetoothdevice.bond_bonded && prevstate == bluetoothdevice.bond_bonding) {                     showtoast("paired");                     connecta2dp(devicebt);                 } else if (state == bluetoothdevice.bond_none && prevstate == bluetoothdevice.bond_bonded){                     showtoast("unpaired");                 } else if (state == bluetoothdevice.bond_none && prevstate == bluetoothdevice.bond_bonding){                     showtoast("pairing rejected, trying again");                     pairdevice(devicebt);                 }              }         }     };     private void connecta2dp(final bluetoothdevice btdevice) {         method connect;         string strmessage = "";         try {             connect = bluetootha2dp.class.getdeclaredmethod("connect", bluetoothdevice.class);             //log.i("connecta2dp","get connect method " + connect);         } catch (nosuchmethodexception ex) {             log.e("connecta2dp", "unable find connect(bluetoothdevice) method in bluetootha2dp proxy.");              return;         }         connect.setaccessible(true);         try {             //log.i("connecta2dp","before invoke" );             connect.invoke(bta2dp, btdevice);             if(btdevice.getbondstate() == bluetoothdevice.bond_bonded)                 strmessage = "success;" + btdevice.getaddress();             else                 strmessage = "failure";              thread fthread = new thread(new finalthread(strmessage));             fthread.start();             //log.i("connecta2dp", "after invoke");         } catch (invocationtargetexception ex) {             log.e("connecta2dp", "unable invoke connect(bluetoothdevice) method on proxy. " + ex.tostring());         } catch (illegalaccessexception ex) {             log.e("connecta2dp", "illegal access! " + ex.tostring());         }     }     @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.menu_main, 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         // specify parent activity in androidmanifest.xml.         int id = item.getitemid();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             return true;         }          return super.onoptionsitemselected(item);     }     public void showtoast(string message)     {         toast.maketext(this, message, toast.length_long).show();     } } 

little explanation of scenario rejects pairing couple of times class start thread on it's oncreate method.now thread continuously monitor port incoming message , once gets message it'll extract mac address of headphones it. once mac address it'll try connect programmatically fails couple of attempts , connects successfully.

thanks


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -