我使用isconnectInternet()
方法来控制我所有类(class)中的手机互联网连接。我这样做了,但每节课都会重复。我如何编写一次并在项目中的任何地方使用它?
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return (mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting());
} else
return false;
}
这是我控制互联网的方法
if(isConnected){
if there is internet conn.
}
else{
there is no internet do samething
}
最佳答案
您可以在另一个类中编写此方法,并在需要时调用它。
public class Common {
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi=cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return (mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting());
} else
return false;
}
}
并通过类名和方法名调用它
if(Common.isConnected ){
if there is internet conn.
}
else{
there is no internet do samething
}
关于java - 我每次都在所有类(class)中使用一种方法。有没有办法只写一次这个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48205211/