sockets - Problems with Android Bluetooth Server and Client -
i have couple problems regarding creating bluetooth server , client multiplayer game i'm making. first problem have searching devices. google provides following code:
// create broadcastreceiver action_found private final broadcastreceiver mreceiver = new broadcastreceiver() { public void onreceive(context context, intent intent) { string action = intent.getaction(); // when discovery finds device if (bluetoothdevice.action_found.equals(action)) { // bluetoothdevice object intent bluetoothdevice device = intent.getparcelableextra(bluetoothdevice.extra_device); // add name , address array adapter show in listview marrayadapter.add(device.getname() + "\n" + device.getaddress()); } } }; // register broadcastreceiver intentfilter filter = new intentfilter(bluetoothdevice.action_found); registerreceiver(mreceiver, filter); // don't forget unregister during ondestroy
but can't find marrayadapter defined or how should like. second question have is, when have server running on device, have connect also, or other phone have connect , server acts client , server?
third question have how connect server. again, google provides code:
private class connectthread extends thread { private final bluetoothsocket mmsocket; private final bluetoothdevice mmdevice; public connectthread(bluetoothdevice device) { // use temporary object later assigned mmsocket, // because mmsocket final bluetoothsocket tmp = null; mmdevice = device; // bluetoothsocket connect given bluetoothdevice try { // my_uuid app's uuid string, used server code tmp = device.createrfcommsockettoservicerecord(my_uuid); } catch (ioexception e) { } mmsocket = tmp; } public void run() { // cancel discovery because slow down connection mbluetoothadapter.canceldiscovery(); try { // connect device through socket. block // until succeeds or throws exception mmsocket.connect(); } catch (ioexception connectexception) { // unable connect; close socket , out try { mmsocket.close(); } catch (ioexception closeexception) { } return; } // work manage connection (in separate thread) manageconnectedsocket(mmsocket); } /** cancel in-progress connection, , close socket */ public void cancel() { try { mmsocket.close(); } catch (ioexception e) { } } }
how create , use class, , variable should pass bluetoothdevice device
in constructor?
thanks :)
you can see marrayadapter.add(device.getname() + "\n" + device.getaddress());
string added. defined as:
arrayadapter<string> mnewdevicesarrayadapter = new arrayadapter<string>(this, r.layout.bluetooth_device_name);
where did code from? complete code can find in devicelistactivity.java of bluetoothchat example app comes sdk many versions again , again.
for second question: 1 app on device makes device visible. other app on other device scanns neighbouring devices , tries connect. both devices have agree.
i advise bluetoothchat app tne examples first. works out of box.
Comments
Post a Comment