main代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean b = NetWorkUtil.isNetWorkAvailable(this);
String ip = getPhoneIp();
//吐司提示
if (b){
Toast.makeText(getApplicationContext(), "当前有可用网络!IP为"+ip,
Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "当前没有可用网络!",
Toast.LENGTH_LONG).show();
}
}
//获取IP的方法
private String getPhoneIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
//if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception e) {
}
return null;
}
}
//判断网络连接的工具类
public class NetWorkUtil {
//判断网络是否连接
public static boolean isNetWorkAvailable(Context context) {
//网络连接管理器
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//网络信息
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null) {
return true;
}
return false;
}
}
希望大家多多支持,评论!!!!