Skip to content

Instantly share code, notes, and snippets.

@darkwave
Created January 6, 2016 21:58
Show Gist options
  • Save darkwave/d5dd7487ebe6b49bc550 to your computer and use it in GitHub Desktop.
Save darkwave/d5dd7487ebe6b49bc550 to your computer and use it in GitHub Desktop.
Bonjour using jmDNS on Processing Android Mode
import javax.jmdns.*;
import java.util.Map;
import java.net.InetAddress;
import java.util.Locale;
import android.net.wifi.WifiManager.MulticastLock;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiInfo;
import android.app.Fragment;
import android.content.Context;
import java.net.UnknownHostException;
Context context;
android.net.wifi.WifiManager.MulticastLock lock;
SampleListener ds;
void setup() {
fullScreen(P2D);
context = getActivity();
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock(getClass().getSimpleName());
lock.setReferenceCounted(false);
try {
InetAddress addr = getLocalIpAddress();
String hostname = addr.getHostName();
lock.acquire();
ds = new SampleListener();
String bonjourServiceType = "_http._tcp.local.";
JmDNS bonjourService = null;
bonjourService = JmDNS.create(addr, hostname);
bonjourService.addServiceListener(bonjourServiceType, ds);
}
catch(Exception ex) {
println(ex);
}
}
static String message = "Status...\n";
void draw() {
background(255);
fill(0);
text(message, 10, 10, width - 10, height - 10);
}
static class SampleListener implements javax.jmdns.ServiceListener {
public void serviceAdded(ServiceEvent event) {
message += "Service added : " + event.getName() + "." + event.getType();
}
public void serviceRemoved(ServiceEvent event) {
message += "Service removed : " + event.getName() + "." + event.getType();
}
public void serviceResolved(ServiceEvent event) {
message += "Service resolved: " + event.getInfo();
}
}
private InetAddress getLocalIpAddress() {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
InetAddress address = null;
try {
address = InetAddress.getByName(String.format(Locale.ENGLISH,
"%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)));
}
catch (UnknownHostException e) {
e.printStackTrace();
}
return address;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment