Android Bluetooth Client Server Connection -
i'hv created simple bluetooth client-server program
bluetooth server:
protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); tv1=(textview)findviewbyid(r.id.textview1); tv2=(textview)findviewbyid(r.id.textview2); mbluetoothadapter=bluetoothadapter.getdefaultadapter(); try { mbluetoothserversocket=mbluetoothadapter.listenusingrfcommwithservicerecord(name,uuid); mbluetoothadapter.canceldiscovery(); mbluetoothsocket=mbluetoothserversocket.accept(); minputstream=mbluetoothsocket.getinputstream(); //if(minputstream.available()>0){ mbufferedreader=new bufferedreader(new inputstreamreader(minputstream)); data = mbufferedreader.readline(); tv1.settext(data); //} if(minputstream.available()>0){ data=mbufferedreader.readline(); tv2.settext(data); x++; } } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } }
bluetooth client :
protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); lb=(button)findviewbyid(r.id.button1); btadapter = bluetoothadapter.getdefaultadapter(); bluetoothdevice device = btadapter.getremotedevice(addresshtc); try { btsocket = device.createrfcommsockettoservicerecord(my_uuid); btadapter.canceldiscovery(); btsocket.connect(); string message = "hello.............. from....... android......\n"; outstream = btsocket.getoutputstream(); byte[] msgbuffer = message.getbytes(); outstream.write(msgbuffer); } catch(ioexception e){ e.printstacktrace(); } lb.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub string m1="msg 2"; byte[] msgbuffer = m1.getbytes(); try { outstream.write(msgbuffer); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }); }
this application passing message , need pass message in server , receive messages contineously...
if have idea. please share it.
this works me contineously reading. try it.
try { bufferedreader reader = new bufferedreader( new inputstreamreader(mmsocket.getinputstream())); while(true) { string receivedmsg; while((receivedmsg = reader.readline()) != null) { // message } } } catch (exception ex) { system.out.println(ex); }
Comments
Post a Comment