6

For multicast purposes, I'm looking for a simple way to detect when the IP of an Android device changes. How can I go about doing so?

More specifically, I'm looking to detect:

  • When the device connects to a new Wifi network and it gets an IP from the DHCP
  • When the device for some reason needs to renew an IP
yydl
  • 24,284
  • 16
  • 65
  • 104

1 Answers1

6

You can do this with the ConnectivityManager:

You can use this to query the current connection state:

ConnectivityManager connMananger = (ConnectivityManager) 
            context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo netInfo = connMananger.getActiveNetworkInfo();

The current IP address of network interfaces can be acquired with NetworkInterface.getNetworkInterfaces()

And you can receive automatic notification of when the connection state changes via the CONNECTIVITY_ACTION broadcast

Thomas Dignan
  • 7,052
  • 3
  • 40
  • 48
  • Sounds good. But does that broadcast only happen when an IP changes, or can lots of different things trigger it? – yydl Dec 23 '11 at 05:03
  • 1
    It can be triggered by any change in connectivity, but I believe there should be some extras to check, or you can detect the differences between NetworkInfo/NetworkInterface objects – Thomas Dignan Dec 23 '11 at 05:09
  • 1
    CONNECTIVITY_ACTION: "This constant was deprecated in API level 28." – cesargastonec Nov 18 '20 at 22:34