How can I detect when the device gets a new IP?
Asked Answered
A

1

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
Aeri answered 23/12, 2011 at 4:38 Comment(0)
S
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

Suffer answered 23/12, 2011 at 4:57 Comment(3)
Sounds good. But does that broadcast only happen when an IP changes, or can lots of different things trigger it?Aeri
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 objectsSuffer
CONNECTIVITY_ACTION: "This constant was deprecated in API level 28."Dariodariole

© 2022 - 2024 — McMap. All rights reserved.