java - Not able to connect to bluetooth devices programmatically -



java - Not able to connect to bluetooth devices programmatically -

my aim connect paired bluetooth devices. have got paired devices names , displaying them in listview. when click on of device name listview should connect device if within range.

whenever seek connect device calling mmsocket.connect() scheme error in log cat shown below , calls mmsocket.close():

06-22 17:40:50.617: w/system.err(25986): java.io.ioexception: read failed, socket might closed or timeout, read ret: -1 06-22 17:40:50.618: w/system.err(25986): @ android.bluetooth.bluetoothsocket.readall(bluetoothsocket.java:510) 06-22 17:40:50.619: w/system.err(25986): @ android.bluetooth.bluetoothsocket.readint(bluetoothsocket.java:521) 06-22 17:40:50.619: w/system.err(25986): @ android.bluetooth.bluetoothsocket.connect(bluetoothsocket.java:320) 06-22 17:40:50.619: w/system.err(25986): @ ik.learning.bluetooth.mainactivity$connectthread.run(mainactivity.java:233)

i not sure why happening can 1 help me out here. below code:

public class mainactivity extends activity implements onitemclicklistener{ arrayadapter<string> listadapter; button connectnew; listview listview; bluetoothadapter btadapter; set<bluetoothdevice> devicesarray; intentfilter filter; broadcastreceiver receiver; arraylist<string> paireddevices; arraylist<bluetoothdevice> devices; public static final uuid my_uuid = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); protected static final int success_connect = 0; protected static final int message_read = 1; handler mhandler; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); init(); if(btadapter == null){ toast.maketext(this, "no bluetooth detected", toast.length_long).show(); finish(); } else { if(!btadapter.isenabled()){ turnonbluetooth(); } getpaireddevices(); startdiscovery(); } mhandler = new handler(){ @override public void handlemessage(message msg) { super.handlemessage(msg); switch(msg.what){ case success_connect: connectedthread connectedthread = new connectedthread((bluetoothsocket) msg.obj); toast.maketext(getapplicationcontext(), "connected", toast.length_short).show(); string s = "successfully connected"; connectedthread.write(s.getbytes()); break; case message_read: byte[] readbuff = (byte[]) msg.obj; string string = new string(readbuff); toast.maketext(getapplicationcontext(), string, toast.length_short).show(); break; } } }; } private void startdiscovery() { // todo auto-generated method stub btadapter.canceldiscovery(); btadapter.startdiscovery(); } private void turnonbluetooth() { // todo auto-generated method stub intent intent = new intent(bluetoothadapter.action_request_enable); startactivityforresult(intent, 1); } private void getpaireddevices() { // todo auto-generated method stub devicesarray = btadapter.getbondeddevices(); if(devicesarray.size() > 0){ for(bluetoothdevice device : devicesarray){ //listadapter.add(device.getname()+"\n"+device.getaddress()); paireddevices.add(device.getname());//+"\n"+device.getaddress()); } } } private void init() { connectnew = (button) findviewbyid(r.id.btnconnectnew); listview = (listview) findviewbyid(r.id.bluetoothlistview); listview.setonitemclicklistener(this); listadapter = new arrayadapter<string>(this, android.r.layout.simple_expandable_list_item_1, 0); listview.setadapter(listadapter); btadapter = bluetoothadapter.getdefaultadapter(); paireddevices = new arraylist<string>(); filter = new intentfilter(bluetoothdevice.action_found); devices = new arraylist<bluetoothdevice>(); receiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { // todo auto-generated method stub string action = intent.getaction(); if(bluetoothdevice.action_found.equals(action)){ bluetoothdevice device = intent.getparcelableextra(bluetoothdevice.extra_device); devices.add(device); string s = ""; for(int = 0; i< paireddevices.size(); i++){ if(device.getname().equals(paireddevices.get(i))){ s = "paired"; break; } } listadapter.add(device.getname()+" ("+s+") "+"\n"+device.getaddress()); } else if(bluetoothadapter.action_discovery_started.equals(action)){ } else if(bluetoothadapter.action_discovery_finished.equals(action)){ } else if(bluetoothadapter.action_state_changed.equals(action)){ if(btadapter.getstate() == btadapter.state_off){ turnonbluetooth(); } } } }; registerreceiver(receiver, filter); filter = new intentfilter(bluetoothadapter.action_discovery_started); registerreceiver(receiver, filter); filter = new intentfilter(bluetoothadapter.action_discovery_finished); registerreceiver(receiver, filter); filter = new intentfilter(bluetoothadapter.action_state_changed); registerreceiver(receiver, filter); } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { // todo auto-generated method stub super.onactivityresult(requestcode, resultcode, data); if(resultcode == result_canceled){ toast.maketext(getapplicationcontext(), "bluetooth must enabled continue", toast.length_short).show(); } } @override protected void onpause() { // todo auto-generated method stub super.onpause(); unregisterreceiver(receiver); } @override public void onitemclick(adapterview<?> arg0, view arg1, int arg2, long arg3) { // todo auto-generated method stub if(btadapter.isdiscovering()){ btadapter.canceldiscovery(); } if(listadapter.getitem(arg2).contains("paired")){ //object[] o = devicesarray.toarray(); bluetoothdevice selecteddevice = devices.get(arg2); connectthread connect = new connectthread(selecteddevice); connect.start(); toast.maketext(getapplicationcontext(), "devices paired", toast.length_short).show(); } else { toast.maketext(getapplicationcontext(), "devices not paired", toast.length_short).show(); } } private class connectthread extends thread { private final bluetoothsocket mmsocket; private final bluetoothdevice mmdevice; public connectthread(bluetoothdevice device) { // utilize temporary object later assigned mmsocket, // because mmsocket final bluetoothsocket tmp = null; mmdevice = device; // bluetoothsocket connect given bluetoothdevice seek { // my_uuid app's uuid string, used server code tmp = device.createrfcommsockettoservicerecord(my_uuid); } grab (ioexception e) { } mmsocket = tmp; } public void run() { // cancel discovery because slow downwards connection btadapter.canceldiscovery(); seek { // connect device through socket. block // until succeeds or throws exception log.d("connectthread","try connect"); //mhandler.obtainmessage(success_connect, mmsocket).sendtotarget(); mmsocket.connect(); } grab (ioexception connectexception) { // unable connect; close socket , out connectexception.printstacktrace(); log.d("connectthread","catch connect: "+connectexception); seek { log.d("connectthread","try soccet close"); mmsocket.close(); } grab (ioexception closeexception) { log.d("connectthread","catch close: "+connectexception); } return; } // work manage connection (in separate thread) log.d("connectthread","before manage connected socket"); //manageconnectedsocket(mmsocket); mhandler.obtainmessage(success_connect, mmsocket).sendtotarget(); } /*private void manageconnectedsocket(bluetoothsocket mmsocket2) { // todo auto-generated method stub }*/ /** cancel in-progress connection, , close socket */ public void cancel() { seek { mmsocket.close(); } grab (ioexception e) { } } } private class connectedthread extends thread { private final bluetoothsocket mmsocket; private final inputstream mminstream; private final outputstream mmoutstream; public connectedthread(bluetoothsocket socket) { mmsocket = socket; inputstream tmpin = null; outputstream tmpout = null; // input , output streams, using temp objects because // fellow member streams final seek { tmpin = socket.getinputstream(); tmpout = socket.getoutputstream(); } grab (ioexception e) { } mminstream = tmpin; mmoutstream = tmpout; } public void run() { byte[] buffer; // buffer store stream int bytes; // bytes returned read() // maintain listening inputstream until exception occurs while (true) { seek { buffer = new byte[1024]; // buffer store stream // read inputstream bytes = mminstream.read(buffer); // send obtained bytes ui activity mhandler.obtainmessage(message_read, bytes, -1, buffer) .sendtotarget(); } grab (ioexception e) { break; } } } /* phone call main activity send info remote device */ public void write(byte[] bytes) { seek { mmoutstream.write(bytes); } grab (ioexception e) { } } /* phone call main activity shutdown connection */ public void cancel() { seek { mmsocket.close(); } grab (ioexception e) { } } } }

after onclick list item bluetooth name, using name can bluetooth device object calling bluetoothadapter.getdefaultadapter().getremotedevice(bluetoothdevice.getaddress());

here sample code connect bluetooth device..

//global variable bluetoothsocket mbsocket; // within run() function mbluetoothadapter = bluetoothadapter.getdefaultadapter(); if(mbluetoothadapter.isenabled()) { seek { for(bluetoothdevice bt: mbluetoothadapter.getbondeddevices()) { if(bt.getname().equalsignorecase(selecteddevice.getname())) { bluetoothdevice device = mbluetoothadapter.getremotedevice(bt.getaddress()); mbluetoothadapter.canceldiscovery(); mbsocket = device.createrfcommsockettoservicerecord(spp_uuid); mbsocket.connect(); homecoming mbsocket; } } } catch(ioexception e) { if(mbsocket != null) { seek { mbsocket.close(); } grab (ioexception e1) { e1.printstacktrace(); } mbsocket = null; } e.printstacktrace(); homecoming null; } } homecoming null;

hope helps.

java android sockets bluetooth

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -