Cross platform communication in Mobile devices-Start Bonjour(Android and iOS)


Communicating cross platform like android to iOS and others is now easier by Bonjour service.if All the devices connected to same network, we can communicate the each other device using this bonjour service.

  • Create a ServerSocket with app defined port and start the service to listen.
  • Implement Bonjour service for android and iOS.
  • Find each other devices and send data through the socket listener.

Android Implementation :

  • Import the jmdns jar in your application.
  • In onCreate of android Activity use following code.
  • Implement jmdns ServiceLisener in Activity.

InetAddress addr = null;
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
WifiInfo wifiinfo = wifi.getConnectionInfo();
int intaddr = wifiinfo.getIpAddress();
addr = storeLocalIPandPort(addr, intaddr);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
    jmdns = JmDNS.create(addr);
    jmdns.addServiceListener(type, listener = new ServiceListener() {
@Override
public void serviceResolved(final ServiceEvent ev) {
final String name = ev.getName();
new Thread(new Runnable() {
@Override
public void run() {
ServiceInfo service =ev.getInfo();
ip = service.getHostAddress();
port = service.getPort();
System.out.println(service.getName()+" "+ service.getURL()+"    "+service.getHostAddress()+"    "+service.getDomain()+"    "+service.getKey()+"  "+service.getProtocol()+" "+service.getPort());
}
}).start();
}
@Override
public void serviceRemoved(ServiceEvent ev) {
final String name = ev.getName();
new Thread(new Runnable() {
@Override
public void run() {
//       removeDeviceFromList(name);
}
}).start();
}
@Override
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_data._tcp.local.", "appname",5000, "plain test service from android");
jmdns.registerService(serviceInfo);
if(activity != null)
{
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
//      Toast.makeText(activity, "Bounjour Service Started", Toast.LENGTH_SHORT).show();
}
});
}
} catch (IOException e) {
e.printStackTrace();
return;
}

Finally in onDestroy Activity release the WiFi lock.