Find Raspberry Pi from Android with mDNS

Raspberry Pi

avahi-daemon settings

Install avahi-daemon (if not included)

sudo apt-get install avahi-daemon

setting change

sudo vi /etc/avahi/avahi-daemon.conf

If it is no, the search could not be done on the Android side.

avahi-daemon.conf


[publish]
publish-workstation=yes

avahi-daemon.service restart

sudo systemctl restart avahi-daemon.service

host name confirmation

cat /etc/hostname
<Hostname>

Android

I think it's faster to see this (reference) https://developer.android.com/training/connect-devices-wirelessly/nsd.html

Get permission

AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET"/>

Member variables


    String TAG = "MainActivity";
    //Change to the confirmed host name
    String serviceName = "<Hostname>";

    private NsdManager nsdManager;
    private NsdManager.DiscoveryListener discoveryListener;
    private NsdManager.ResolveListener resolveListener;
    private NsdServiceInfo mService;

Initialize

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nsdManager = (NsdManager)(getApplicationContext().getSystemService(Context.NSD_SERVICE));
        initializeResolveListener();
        initializeDiscoveryListener();
        nsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, discoveryListener);
    }

Function definition


    public void initializeDiscoveryListener() {

        discoveryListener = new NsdManager.DiscoveryListener() {

            @Override
            public void onDiscoveryStarted(String regType) {
                Log.d(TAG, "Service discovery started");
            }

            @Override
            public void onServiceFound(NsdServiceInfo service) {
                //Can be found<hostname>.local[<mac address>]It was like, so I corresponded with contains
                if (service.getServiceName().contains(serviceName)) {
                    nsdManager.resolveService(service, resolveListener);
                    Log.d(TAG, "Same machine: " + serviceName);
                } 
            }

            @Override
            public void onServiceLost(NsdServiceInfo service) {
                Log.e(TAG, "service lost: " + service);
            }

            @Override
            public void onDiscoveryStopped(String serviceType) {
                Log.i(TAG, "Discovery stopped: " + serviceType);
            }

            @Override
            public void onStartDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code:" + errorCode);
                nsdManager.stopServiceDiscovery(this);
            }

            @Override
            public void onStopDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code:" + errorCode);
                nsdManager.stopServiceDiscovery(this);
            }
        };
    }


    public void initializeResolveListener() {
        resolveListener = new NsdManager.ResolveListener() {

            @Override
            public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Called when the resolve fails. Use the error code to debug.
                Log.e(TAG, "Resolve failed: " + errorCode);
            }

            @Override
            public void onServiceResolved(NsdServiceInfo serviceInfo) {
                Log.e(TAG, "Resolve Succeeded. " + serviceInfo);

                if (serviceInfo.getServiceName().equals(serviceName)) {
                    Log.d(TAG, "Same IP.");
                    return;
                }
                mService = serviceInfo;
                int port = mService.getPort();
                InetAddress host = mService.getHost();
            }
        };
    }

Full text

MainActivity.java



public class MainActivity extends AppCompatActivity {

    String TAG = "MainActivity";
    //Change to the confirmed host name
    String serviceName = "<Hostname>";

    private NsdManager nsdManager;
    private NsdManager.DiscoveryListener discoveryListener;
    private NsdManager.ResolveListener resolveListener;
    private NsdServiceInfo mService;

    // raspberry service type
    private static final String SERVICE_TYPE = "_workstation._tcp.";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nsdManager = (NsdManager)(getApplicationContext().getSystemService(Context.NSD_SERVICE));
        initializeResolveListener();
        initializeDiscoveryListener();
        nsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, discoveryListener);
    }

    public void initializeDiscoveryListener() {

        discoveryListener = new NsdManager.DiscoveryListener() {

            @Override
            public void onDiscoveryStarted(String regType) {
                Log.d(TAG, "Service discovery started");
            }

            @Override
            public void onServiceFound(NsdServiceInfo service) {
                Log.d(TAG, "Service discovery success" + service);


                if (!service.getServiceType().equals(SERVICE_TYPE)) {
                    Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
                } else if (service.getServiceName().equals(serviceName)) {
                    Log.d(TAG, "Same machine: " + serviceName);
                } else if (service.getServiceName().contains("NsdChat")){
                    nsdManager.resolveService(service, resolveListener);
                }
            }

            @Override
            public void onServiceLost(NsdServiceInfo service) {
                Log.e(TAG, "service lost: " + service);
            }

            @Override
            public void onDiscoveryStopped(String serviceType) {
                Log.i(TAG, "Discovery stopped: " + serviceType);
            }

            @Override
            public void onStartDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code:" + errorCode);
                nsdManager.stopServiceDiscovery(this);
            }

            @Override
            public void onStopDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code:" + errorCode);
                nsdManager.stopServiceDiscovery(this);
            }
        };
    }


    public void initializeResolveListener() {
        resolveListener = new NsdManager.ResolveListener() {

            @Override
            public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Called when the resolve fails. Use the error code to debug.
                Log.e(TAG, "Resolve failed: " + errorCode);
            }

            @Override
            public void onServiceResolved(NsdServiceInfo serviceInfo) {
                Log.e(TAG, "Resolve Succeeded. " + serviceInfo);

                if (serviceInfo.getServiceName().equals(serviceName)) {
                    Log.d(TAG, "Same IP.");
                    return;
                }
                mService = serviceInfo;
                int port = mService.getPort();
                //Wanted host name
                InetAddress host = mService.getHost();
            }
        };
    }
}

Recommended Posts

Find Raspberry Pi from Android with mDNS
Read temperature / humidity with Java from Raspberry Pi 3 & DHT11
Read barometric pressure and temperature with Java from Raspberry Pi 3 & BMP180
Launched Redmine with Docker on Raspberry Pi 3
[Android] Read from QR code image with zxing
I couldn't install docker with raspberry pi2 b +.
How to run javafx with Raspberry Pi Posted on 2020/07/12
Play down with Raspberry PI4 as a server. Part 2
Vibrate the wristband device with Bluetooth from the Android app
Display characters on I2C 1602 LCD with Raspberry Pi 3 & Java
Build an Android image for Orange Pi 4 with Docker
Compatible with Android 10 (API 29)
Find the address class and address type from the IP address with Java
[MT] Specify the article category from Android with Data API
Check communication from Android to node.js server with protocol buffers
[MT] Specify the article category from Android with Data API