bluetooth - Send Text from Bluecove Java Server to Android app and vice versa -
i'm new java , android , iv'e been following tutorials , other websites. firstly, created 'androidchat' app , created java application using bluecove on ubuntu virtual machine. i'm struggling work out how can android app , bluetooth server send , receive data each other. want server output text sent android app, , server send text console android app. close or difficult implement. code great! have far:
android client app (bluetoothconnectionservice.java)
public class bluetoothconnectionservice { private static final string tag = "toby-virtualbox"; private static final string appname = "bluetooth chat app"; private static final uuid my_uuid_insecure = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); //00001101-0000-1000-8000-00805f9b34fb private final bluetoothadapter mbluetoothadapter; context mcontext; private acceptthread minsecureacceptthread; private connectthread mconnectthread; private bluetoothdevice mmdevice; private uuid deviceuuid; progressdialog mprogressdialog; private connectedthread mconnectedthread; public bluetoothconnectionservice(context context) { mcontext = context; mbluetoothadapter = bluetoothadapter.getdefaultadapter(); start(); } /** * thread runs while listening incoming connections. behaves * server-side client. runs until connection accepted * (or until cancelled). */ private class acceptthread extends thread { // local server socket private final bluetoothserversocket mmserversocket; public acceptthread(){ bluetoothserversocket tmp = null; // create new listening server socket try{ tmp = mbluetoothadapter.listenusinginsecurerfcommwithservicerecord(appname, my_uuid_insecure); log.d(tag, "acceptthread: setting server using: " + my_uuid_insecure); }catch (ioexception e){ log.e(tag, "acceptthread: ioexception: " + e.getmessage() ); } mmserversocket = tmp; } public void run(){ log.d(tag, "run: acceptthread running."); bluetoothsocket socket = null; try{ // blocking call , return on // successful connection or exception log.d(tag, "run: rfcom server socket start....."); socket = mmserversocket.accept(); log.d(tag, "run: rfcom server socket accepted connection."); }catch (ioexception e){ log.e(tag, "acceptthread: ioexception: " + e.getmessage() ); } //talk in 3rd if(socket != null){ connected(socket,mmdevice); } log.i(tag, "end macceptthread "); } public void cancel() { log.d(tag, "cancel: canceling acceptthread."); try { mmserversocket.close(); } catch (ioexception e) { log.e(tag, "cancel: close of acceptthread serversocket failed. " + e.getmessage() ); } } } /** * thread runs while attempting make outgoing connection * device. runs straight through; connection either * succeeds or fails. */ private class connectthread extends thread { private bluetoothsocket mmsocket; public connectthread(bluetoothdevice device, uuid uuid) { log.d(tag, "connectthread: started."); mmdevice = device; deviceuuid = uuid; } public void run(){ bluetoothsocket tmp = null; log.i(tag, "run mconnectthread "); // bluetoothsocket connection // given bluetoothdevice try { log.d(tag, "connectthread: trying create insecurerfcommsocket using uuid: " +my_uuid_insecure ); tmp = mmdevice.createrfcommsockettoservicerecord(deviceuuid); } catch (ioexception e) { log.e(tag, "connectthread: not create insecurerfcommsocket " + e.getmessage()); } mmsocket = tmp; // cancel discovery because slow down connection mbluetoothadapter.canceldiscovery(); // make connection bluetoothsocket try { // blocking call , return on // successful connection or exception mmsocket.connect(); log.d(tag, "run: connectthread connected."); } catch (ioexception e) { // close socket try { mmsocket.close(); log.d(tag, "run: closed socket."); } catch (ioexception e1) { log.e(tag, "mconnectthread: run: unable close connection in socket " + e1.getmessage()); } log.d(tag, "run: connectthread: not connect uuid: " + my_uuid_insecure ); } //will talk in 3rd video connected(mmsocket,mmdevice); } public void cancel() { try { log.d(tag, "cancel: closing client socket."); mmsocket.close(); } catch (ioexception e) { log.e(tag, "cancel: close() of mmsocket in connectthread failed. " + e.getmessage()); } } } /** * start chat service. start acceptthread begin * session in listening (server) mode. called activity onresume() */ public synchronized void start() { log.d(tag, "start"); // cancel thread attempting make connection if (mconnectthread != null) { mconnectthread.cancel(); mconnectthread = null; } if (minsecureacceptthread == null) { minsecureacceptthread = new acceptthread(); minsecureacceptthread.start(); } } /** acceptthread starts , sits waiting connection. connectthread starts , attempts make connection other devices acceptthread. **/ public void startclient(bluetoothdevice device,uuid uuid){ log.d(tag, "startclient: started."); //initprogress dialog mprogressdialog = progressdialog.show(mcontext,"connecting bluetooth" ,"please wait...",true); mconnectthread = new connectthread(device, uuid); mconnectthread.start(); } /** connectedthread responsible maintaining btconnection, sending data, , receiving incoming data through input/output streams respectively. **/ private class connectedthread extends thread { private final bluetoothsocket mmsocket; private final inputstream mminstream; private final outputstream mmoutstream; public connectedthread(bluetoothsocket socket) { log.d(tag, "connectedthread: starting."); mmsocket = socket; inputstream tmpin = null; outputstream tmpout = null; //dismiss progressdialog when connection established try{ mprogressdialog.dismiss(); }catch (nullpointerexception e){ e.printstacktrace(); } try { tmpin = mmsocket.getinputstream(); tmpout = mmsocket.getoutputstream(); } catch (ioexception e) { e.printstacktrace(); } 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) { // read inputstream try { bytes = mminstream.read(buffer); string incomingmessage = new string(buffer, 0, bytes); log.d(tag, "inputstream: " + incomingmessage); } catch (ioexception e) { log.e(tag, "write: error reading input stream. " + e.getmessage() ); break; } } } //call main activity send data remote device public void write(byte[] bytes) { string text = new string(bytes, charset.defaultcharset()); log.d(tag, "write: writing outputstream: " + text); try { mmoutstream.write(bytes); } catch (ioexception e) { log.e(tag, "write: error writing output stream. " + e.getmessage() ); } } /* call main activity shutdown connection */ public void cancel() { try { mmsocket.close(); } catch (ioexception e) { } } } private void connected(bluetoothsocket mmsocket, bluetoothdevice mmdevice) { log.d(tag, "connected: starting."); // start thread manage connection , perform transmissions mconnectedthread = new connectedthread(mmsocket); mconnectedthread.start(); } /** * write connectedthread in unsynchronized manner * * @param out bytes write * @see connectedthread#write(byte[]) */ public void write(byte[] out) { // create temporary object connectedthread r; // synchronize copy of connectedthread log.d(tag, "write: write called."); //perform write mconnectedthread.write(out); } } android client app (mainactivity.java)
public class mainactivity extends appcompatactivity implements adapterview.onitemclicklistener{ private static final string tag = "mainactivity"; bluetoothadapter mbluetoothadapter; button btnenabledisable_discoverable; bluetoothconnectionservice mbluetoothconnection; button btnstartconnection; button btnsend; edittext etsend; private static final uuid my_uuid_insecure = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); bluetoothdevice mbtdevice; public arraylist<bluetoothdevice> mbtdevices = new arraylist<>(); public devicelistadapter mdevicelistadapter; listview lvnewdevices; // create broadcastreceiver action_found private final broadcastreceiver mbroadcastreceiver1 = new broadcastreceiver() { public void onreceive(context context, intent intent) { string action = intent.getaction(); // when discovery finds device if (action.equals(mbluetoothadapter.action_state_changed)) { final int state = intent.getintextra(bluetoothadapter.extra_state, mbluetoothadapter.error); switch(state){ case bluetoothadapter.state_off: log.d(tag, "onreceive: state off"); break; case bluetoothadapter.state_turning_off: log.d(tag, "mbroadcastreceiver1: state turning off"); break; case bluetoothadapter.state_on: log.d(tag, "mbroadcastreceiver1: state on"); break; case bluetoothadapter.state_turning_on: log.d(tag, "mbroadcastreceiver1: state turning on"); break; } } } }; /** * broadcast receiver changes made bluetooth states such as: * 1) discoverability mode on/off or expire. */ private final broadcastreceiver mbroadcastreceiver2 = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { final string action = intent.getaction(); if (action.equals(bluetoothadapter.action_scan_mode_changed)) { int mode = intent.getintextra(bluetoothadapter.extra_scan_mode, bluetoothadapter.error); switch (mode) { //device in discoverable mode case bluetoothadapter.scan_mode_connectable_discoverable: log.d(tag, "mbroadcastreceiver2: discoverability enabled."); break; //device not in discoverable mode case bluetoothadapter.scan_mode_connectable: log.d(tag, "mbroadcastreceiver2: discoverability disabled. able receive connections."); break; case bluetoothadapter.scan_mode_none: log.d(tag, "mbroadcastreceiver2: discoverability disabled. not able receive connections."); break; case bluetoothadapter.state_connecting: log.d(tag, "mbroadcastreceiver2: connecting...."); break; case bluetoothadapter.state_connected: log.d(tag, "mbroadcastreceiver2: connected."); break; } } } }; /** * broadcast receiver listing devices not yet paired * -executed btndiscover() method. */ private broadcastreceiver mbroadcastreceiver3 = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { final string action = intent.getaction(); log.d(tag, "onreceive: action found."); if (action.equals(bluetoothdevice.action_found)){ bluetoothdevice device = intent.getparcelableextra (bluetoothdevice.extra_device); mbtdevices.add(device); log.d(tag, "onreceive: " + device.getname() + ": " + device.getaddress()); mdevicelistadapter = new devicelistadapter(context, r.layout.device_adapter_view, mbtdevices); lvnewdevices.setadapter(mdevicelistadapter); } } }; /** * broadcast receiver detects bond state changes (pairing status changes) */ private final broadcastreceiver mbroadcastreceiver4 = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { final string action = intent.getaction(); if(action.equals(bluetoothdevice.action_bond_state_changed)){ bluetoothdevice mdevice = intent.getparcelableextra(bluetoothdevice.extra_device); //3 cases: //case1: bonded if (mdevice.getbondstate() == bluetoothdevice.bond_bonded){ log.d(tag, "broadcastreceiver: bond_bonded."); //inside broadcastreceiver4 mbtdevice = mdevice; } //case2: creating bone if (mdevice.getbondstate() == bluetoothdevice.bond_bonding) { log.d(tag, "broadcastreceiver: bond_bonding."); } //case3: breaking bond if (mdevice.getbondstate() == bluetoothdevice.bond_none) { log.d(tag, "broadcastreceiver: bond_none."); } } } }; @override protected void ondestroy() { log.d(tag, "ondestroy: called."); super.ondestroy(); unregisterreceiver(mbroadcastreceiver1); unregisterreceiver(mbroadcastreceiver2); unregisterreceiver(mbroadcastreceiver3); unregisterreceiver(mbroadcastreceiver4); //mbluetoothadapter.canceldiscovery(); } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); button btnonoff = (button) findviewbyid(r.id.btnonoff); btnenabledisable_discoverable = (button) findviewbyid(r.id.btndiscoverable_on_off); lvnewdevices = (listview) findviewbyid(r.id.lvnewdevices); mbtdevices = new arraylist<>(); btnstartconnection = (button) findviewbyid(r.id.btnstartconnection); btnsend = (button) findviewbyid(r.id.btnsend); etsend = (edittext) findviewbyid(r.id.edittext); //broadcasts when bond state changes (ie:pairing) intentfilter filter = new intentfilter(bluetoothdevice.action_bond_state_changed); registerreceiver(mbroadcastreceiver4, filter); mbluetoothadapter = bluetoothadapter.getdefaultadapter(); lvnewdevices.setonitemclicklistener(mainactivity.this); btnonoff.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { log.d(tag, "onclick: enabling/disabling bluetooth."); enabledisablebt(); } }); btnstartconnection.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { startconnection(); } }); btnsend.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { byte[] bytes = etsend.gettext().tostring().getbytes(charset.defaultcharset()); mbluetoothconnection.write(bytes); } }); } //create method starting connection //***remember connction fail , app crash if haven't paired first public void startconnection(){ startbtconnection(mbtdevice,my_uuid_insecure); } /** * starting chat service method */ public void startbtconnection(bluetoothdevice device, uuid uuid){ log.d(tag, "startbtconnection: initializing rfcom bluetooth connection."); mbluetoothconnection.startclient(device,uuid); } public void enabledisablebt(){ if(mbluetoothadapter == null){ log.d(tag, "enabledisablebt: not have bt capabilities."); } if(!mbluetoothadapter.isenabled()){ log.d(tag, "enabledisablebt: enabling bt."); intent enablebtintent = new intent(bluetoothadapter.action_request_enable); startactivity(enablebtintent); intentfilter btintent = new intentfilter(bluetoothadapter.action_state_changed); registerreceiver(mbroadcastreceiver1, btintent); } if(mbluetoothadapter.isenabled()){ log.d(tag, "enabledisablebt: disabling bt."); mbluetoothadapter.disable(); intentfilter btintent = new intentfilter(bluetoothadapter.action_state_changed); registerreceiver(mbroadcastreceiver1, btintent); } } public void btnenabledisable_discoverable(view view) { log.d(tag, "btnenabledisable_discoverable: making device discoverable 300 seconds."); intent discoverableintent = new intent(bluetoothadapter.action_request_discoverable); discoverableintent.putextra(bluetoothadapter.extra_discoverable_duration, 300); startactivity(discoverableintent); intentfilter intentfilter = new intentfilter(mbluetoothadapter.action_scan_mode_changed); registerreceiver(mbroadcastreceiver2,intentfilter); } public void btndiscover(view view) { log.d(tag, "btndiscover: looking unpaired devices."); if(mbluetoothadapter.isdiscovering()){ mbluetoothadapter.canceldiscovery(); log.d(tag, "btndiscover: canceling discovery."); //check bt permissions in manifest mbluetoothadapter.startdiscovery(); intentfilter discoverdevicesintent = new intentfilter(bluetoothdevice.action_found); registerreceiver(mbroadcastreceiver3, discoverdevicesintent); } if(!mbluetoothadapter.isdiscovering()){ //check bt permissions in manifest mbluetoothadapter.startdiscovery(); intentfilter discoverdevicesintent = new intentfilter(bluetoothdevice.action_found); registerreceiver(mbroadcastreceiver3, discoverdevicesintent); } } @override public void onitemclick(adapterview<?> adapterview, view view, int i, long l) { //first cancel discovery because memory intensive. mbluetoothadapter.canceldiscovery(); log.d(tag, "onitemclick: clicked on device."); string devicename = mbtdevices.get(i).getname(); string deviceaddress = mbtdevices.get(i).getaddress(); log.d(tag, "onitemclick: devicename = " + devicename); log.d(tag, "onitemclick: deviceaddress = " + deviceaddress); //create bond. //note: requires api 17+? think jellybean if(build.version.sdk_int > build.version_codes.jelly_bean_mr2){ log.d(tag, "trying pair " + devicename); mbtdevices.get(i).createbond(); mbtdevice = mbtdevices.get(i); mbluetoothconnection = new bluetoothconnectionservice(mainactivity.this); } } } server application
public class samplesppserver { //start server private void startserver() throws ioexception{ //create uuid spp uuid uuid = new uuid(“0000110100001000800000805f9b34fb″, false); //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”); string output = system.console().readline(); pwriter.write(output); 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()); samplesppserver samplesppserver=new samplesppserver(); samplesppserver.startserver(); } }
Comments
Post a Comment