java - Connect bluetooth from android to computer(paired devices) -


so, want application connect pc , use android touch pad. iv been doing lot of research on net, didn't find anywhere how connect phone pc. made pair device function , else, need connection method, or @ least how done. here code:

public class mainactivity extends activity { private bluetoothadapter adapter; private intent turnon; private set<bluetoothdevice> paireddevices; private listview lv; private button on,off,paireddevice,discoverable,neardevices; private list<bluetoothdevice> discovereddevices = new arraylist<bluetoothdevice>(); private  handler mhandler; private static final uuid my_uuid = uuid.fromstring("04c6093b-0000-1000-8000-00805f9b34fb"); @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);     initialize();     buttonfunc();     find(); }   @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 lista(int i){     if(i==0) {         final deviceadapter deviceadapter = new deviceadapter(mainactivity.this, discovereddevices);         lv.setadapter(deviceadapter);         lv.setonitemclicklistener(new adapterview.onitemclicklistener() {             @override             public void onitemclick(adapterview<?> parent, view view, int position, long id) {                 pairdevice(deviceadapter.getitem(position));                 message.message(mainactivity.this, deviceadapter.getitem(position).getname().tostring());             }         });     }     else if(i == 1){         list<bluetoothdevice> vecupareni = new arraylist<bluetoothdevice>();          (bluetoothdevice bt:adapter.getbondeddevices()){             vecupareni.add(bt);         }         final deviceadapter deviceadapter = new deviceadapter(mainactivity.this,  vecupareni);         lv.setadapter(deviceadapter);         lv.setonitemclicklistener(new adapterview.onitemclicklistener() {             @override             public void onitemclick(adapterview<?> parent, view view, int position, long id) {                 string adresa = deviceadapter.getitem(position).getaddress();                 method connect = getconnectmethod();                 bluetoothdevice device = deviceadapter.getitem(position);               }         });     } }   private method getconnectmethod () {     try {         return bluetootha2dp.class.getdeclaredmethod("connect", bluetoothdevice.class);     } catch (nosuchmethodexception ex) {         message.message(mainactivity.this , "unable connect");         return null;     } }   private void pairdevice(bluetoothdevice device) {     try {         log.d("pairdevice()", "start pairing...");         method m = device.getclass().getmethod("createbond", (class[]) null);         m.invoke(device, (object[]) null);         log.d("pairdevice()", "pairing finished.");     } catch (exception e) {         log.e("pairdevice()", e.getmessage());     } }  public void buttonfunc(){     on.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             turnon = new intent(bluetoothadapter.action_request_enable);             startactivityforresult(turnon,0);             message.message(mainactivity.this , "bluetooth enabled");         }     });     off.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             adapter.disable();         }     });     paireddevice.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {         lista(1);         }     });     discoverable.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             intent discoverableintent = new                     intent(bluetoothadapter.action_request_discoverable);             discoverableintent.putextra(bluetoothadapter.extra_discoverable_duration, 1);             startactivity(discoverableintent);         }     });     neardevices.setonclicklistener(new onclicklistener() {         @override         public void onclick(view v) {             lista(0);         }     }); }    public void find(){     intentfilter filter = new intentfilter();      filter.addaction(bluetoothdevice.action_found);     filter.addaction(bluetoothadapter.action_discovery_started);     filter.addaction(bluetoothadapter.action_discovery_finished);      registerreceiver(mreceiver, filter);     adapter.startdiscovery(); }  private final broadcastreceiver mreceiver = new broadcastreceiver() {     public void onreceive(context context, intent intent) {         string action = intent.getaction();          if (bluetoothadapter.action_discovery_started.equals(action)) {             //discovery starts, can show progress dialog or perform other tasks         } else if (bluetoothadapter.action_discovery_finished.equals(action)) {             //discovery finishes, dismis progress dialog         } else if (bluetoothdevice.action_found.equals(action)) {             //bluetooth device found             bluetoothdevice device = (bluetoothdevice) intent.getparcelableextra(bluetoothdevice.extra_device);             discovereddevices.add(device);             message.message(mainactivity.this, "found device " + device.getname());             lista(0);         }     } };       public void initialize(){     on = (button) findviewbyid(r.id.on);     off = (button) findviewbyid(r.id.off);     paireddevice = (button) findviewbyid(r.id.paireddevices);     neardevices = (button) findviewbyid(r.id.neardevices);     discoverable = (button) findviewbyid(r.id.makediscoverable);     lv = (listview) findviewbyid(r.id.listauredjaja);     adapter = bluetoothadapter.getdefaultadapter();     if(adapter == null){         system.out.close();     }     if(adapter.isenabled()){         message.message(mainactivity.this , "enabled");     }     else{         message.message(mainactivity.this , "not enabled");     } } 

}

and here server on pc awaiting connection:

public class mejn {  //start server private void startserver() throws ioexception{      //create uuid spp     uuid uuid = new uuid("1101", true);     //create servicve url     string connectionstring = "btspp://localhost:" + uuid +";name=sample spp server";      //open server url     streamconnectionnotifier streamconnnotifier = (streamconnectionnotifier)connector.open( connectionstring );      //wait client connection     system.out.println("\nserver started. waiting clients connect...");     streamconnection connection=streamconnnotifier.acceptandopen();      remotedevice dev = remotedevice.getremotedevice(connection);     system.out.println("remote device address: "+dev.getbluetoothaddress());     system.out.println("remote device name: "+dev.getfriendlyname(true));      //read string spp client     inputstream instream=connection.openinputstream();     bufferedreader breader=new bufferedreader(new inputstreamreader(instream));     string lineread=breader.readline();     system.out.println(lineread);      //send response spp client     outputstream outstream=connection.openoutputstream();     printwriter pwriter=new printwriter(new outputstreamwriter(outstream));     pwriter.write("response string spp server\r\n");     pwriter.flush();      pwriter.close();     streamconnnotifier.close();  }   public static void main(string[] args) throws ioexception {      //display local device address , name     localdevice localdevice = localdevice.getlocaldevice();     system.out.println("address: "+localdevice.getbluetoothaddress());     system.out.println("name: "+localdevice.getfriendlyname());      mejn samplesppserver=new mejn();     samplesppserver.startserver();  } 

}

so, while looking more, found somewhere , put in code, here code:

public class mainactivity extends activity { private bluetoothadapter adapter; private intent turnon; private set<bluetoothdevice> paireddevices; private listview lv; private button on,off,paireddevice,discoverable,neardevices; private list<bluetoothdevice> discovereddevices = new arraylist<bluetoothdevice>(); private bluetoothsocket btsocket = null; public outputstream outstream; private static final uuid my_uuid =         uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); private static string address = "c01885bd823c"; @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);     initialize();     buttonfunc();     find(); }   @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 lista(int i){     if(i==0) {         final deviceadapter deviceadapter = new deviceadapter(mainactivity.this, discovereddevices);         lv.setadapter(deviceadapter);         lv.setonitemclicklistener(new adapterview.onitemclicklistener() {             @override             public void onitemclick(adapterview<?> parent, view view, int position, long id) {                 pairdevice(deviceadapter.getitem(position));                 message.message(mainactivity.this, deviceadapter.getitem(position).getname().tostring());             }         });     }     else if(i == 1){         list<bluetoothdevice> vecupareni = new arraylist<bluetoothdevice>();          (bluetoothdevice bt:adapter.getbondeddevices()){             vecupareni.add(bt);         }         final deviceadapter deviceadapter = new deviceadapter(mainactivity.this,  vecupareni);         lv.setadapter(deviceadapter);         lv.setonitemclicklistener(new adapterview.onitemclicklistener() {             @override             public void onitemclick(adapterview<?> parent, view view, int position, long id) {                 bluetoothdevice device = adapter.getremotedevice(deviceadapter.getitem(position).getaddress());                 try {                     btsocket = device.createrfcommsockettoservicerecord(my_uuid);                 } catch (ioexception e) {                     message.message(mainactivity.this , "in onresume() , socket create failed: " + e.tostring() + ".");                 }                 adapter.canceldiscovery();                 try {                     btsocket.connect();                     system.out.print("\n...connection established , data link opened...");                 } catch (ioexception e) {                     try {                         btsocket.close();                     } catch (ioexception e2) {                         message.message(mainactivity.this , "in onresume() , unable close socket during connection failure" + e2.getmessage().tostring() + ".");                     }                 }                 try {                     outstream = btsocket.getoutputstream();                 } catch (ioexception e) {                     message.message(mainactivity.this , "in onresume() , output stream creation failed:" + e.getmessage() + ".");                 }                 system.out.print("\n...sending message server...");                 string message = "hello android.\n";                 system.out.print("\n\n...the message send server is: "+message);                 byte[] msgbuffer = message.getbytes();                 try {                     outstream.write(message.getbytes());                 } catch (ioexception e) {                     string msg = "in onresume() , exception occurred during write: " + e.getmessage();                     if (address.equals("00:00:00:00:00:00"))                         msg = msg + ".\n\nupdate server address 00:00:00:00:00:00 correct address on line 37 in java code";                     msg = msg +  ".\n\ncheck spp uuid: " + my_uuid.tostring() + " exists on server.\n\n";                      message.message(mainactivity.this , msg);                 }                }         });     } }   private method getconnectmethod () {     try {         return bluetootha2dp.class.getdeclaredmethod("connect", bluetoothdevice.class);     } catch (nosuchmethodexception ex) {         message.message(mainactivity.this , "unable connect");         return null;     } }   private void pairdevice(bluetoothdevice device) {     try {         log.d("pairdevice()", "start pairing...");         method m = device.getclass().getmethod("createbond", (class[]) null);         m.invoke(device, (object[]) null);         log.d("pairdevice()", "pairing finished.");     } catch (exception e) {         log.e("pairdevice()", e.getmessage());     } }  public void buttonfunc(){     on.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             turnon = new intent(bluetoothadapter.action_request_enable);             startactivityforresult(turnon,0);             message.message(mainactivity.this , "bluetooth enabled");         }     });     off.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             adapter.disable();         }     });     paireddevice.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {         lista(1);         }     });     discoverable.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             intent discoverableintent = new                     intent(bluetoothadapter.action_request_discoverable);             discoverableintent.putextra(bluetoothadapter.extra_discoverable_duration, 1);             startactivity(discoverableintent);         }     });     neardevices.setonclicklistener(new onclicklistener() {         @override         public void onclick(view v) {             lista(0);         }     }); }    public void find(){     intentfilter filter = new intentfilter();      filter.addaction(bluetoothdevice.action_found);     filter.addaction(bluetoothadapter.action_discovery_started);     filter.addaction(bluetoothadapter.action_discovery_finished);      registerreceiver(mreceiver, filter);     adapter.startdiscovery(); }  private final broadcastreceiver mreceiver = new broadcastreceiver() {     public void onreceive(context context, intent intent) {         string action = intent.getaction();          if (bluetoothadapter.action_discovery_started.equals(action)) {             //discovery starts, can show progress dialog or perform other tasks         } else if (bluetoothadapter.action_discovery_finished.equals(action)) {             //discovery finishes, dismis progress dialog         } else if (bluetoothdevice.action_found.equals(action)) {             //bluetooth device found             bluetoothdevice device = (bluetoothdevice) intent.getparcelableextra(bluetoothdevice.extra_device);             discovereddevices.add(device);             message.message(mainactivity.this, "found device " + device.getname());             lista(0);         }     } };       public void initialize(){     on = (button) findviewbyid(r.id.on);     off = (button) findviewbyid(r.id.off);     paireddevice = (button) findviewbyid(r.id.paireddevices);     neardevices = (button) findviewbyid(r.id.neardevices);     discoverable = (button) findviewbyid(r.id.makediscoverable);     lv = (listview) findviewbyid(r.id.listauredjaja);     adapter = bluetoothadapter.getdefaultadapter();     if(adapter == null){         system.out.close();     }     if(adapter.isenabled()){         message.message(mainactivity.this , "enabled");     }     else{         message.message(mainactivity.this , "not enabled");     } } 

}

and code server:

/** * class implements spp server accepts single line of * message spp client , sends single line of response client. */ public class mejn {

//start server private void startserver() throws ioexception{      //create uuid spp     uuid uuid = new uuid("1101", true);     //create servicve url     string connectionstring = "btspp://localhost:" + uuid +";name=sample spp server";      //open server url     streamconnectionnotifier streamconnnotifier = (streamconnectionnotifier)connector.open( connectionstring );      //wait client connection     system.out.println("\nserver started. waiting clients connect...");     streamconnection connection=streamconnnotifier.acceptandopen();      remotedevice dev = remotedevice.getremotedevice(connection);     system.out.println("remote device address: "+dev.getbluetoothaddress());     system.out.println("remote device name: "+dev.getfriendlyname(true));      //read string spp client     inputstream instream=connection.openinputstream();     bufferedreader breader=new bufferedreader(new inputstreamreader(instream));     string lineread=breader.readline();     system.out.println(lineread);      //send response spp client     outputstream outstream=connection.openoutputstream();     printwriter pwriter=new printwriter(new outputstreamwriter(outstream));     pwriter.write("response string spp server\r\n");     pwriter.flush();      pwriter.close();      streamconnnotifier.close();  }   public static void main(string[] args) throws ioexception {      //display local device address , name     localdevice localdevice = localdevice.getlocaldevice();     system.out.println("address: "+localdevice.getbluetoothaddress());     system.out.println("name: "+localdevice.getfriendlyname());      mejn samplesppserver=new mejn();     samplesppserver.startserver();  } 

}


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -