This is continuation for Eng.Fouad answer, which is by Parse the public IP address from checkip.org (Using JSoup)::
Method (Incase if you receive exception error from previous method):
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
**********
public static String getPublicIp()
{
String myip="";
try{
Document doc = Jsoup.connect("http://www.checkip.org").get();
myip = doc.getElementById("yourip").select("h1").first().select("span").text();
}
catch(IOException e){
e.printStackTrace();
}
return myip;
}
Calling method example:
<your class name> wifiInfo = new <your class name>();
String myIP = wifiInfo.getPublicIp();
Compile following library in your build.gradle dependencies
compile 'org.jsoup:jsoup:1.9.2'
JSoup is compiled using Java API Version 8, so add following inside build.gradle defaultConfig {}
jackOptions{
enabled true
}
and change compile option to:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Last but not least, place following code under the onCreate() method, as by default you're not supposed to run network operation by UI (recomended via services or AsyncTask) then rebuild the code.
StrictMode.enableDefaults();
Tested and working on Lolipop and Kitkat.