Android网络类型判断及IP地址获取

轉載自 http://blog.csdn.net/dodod2012/article/details/51305739

 

参考地址:http://blog.sina.com.cn/s/blog_5da93c8f0102vg21.html

http://www.cnblogs.com/android100/p/Android-get-ip.html

http://blog.csdn.net/xundh/article/details/44916177

用户权限:

<uses-permission android:name="android.permission.INTERNET">uses-permission>    
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE">uses-permission>    
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE">uses-permission>    
<uses-permission android:name="android.permission.WAKE_LOCK">uses-permission>    
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>    

判断有无网络连接:

复制代码
ConnectivityManager mConnectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);   
TelephonyManager mTelephony = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE);   
//检查网络连接   
NetworkInfo info = mConnectivity.getActiveNetworkInfo();   
  
if (info == null || !mConnectivity.getBackgroundDataSetting()) {   
return false;   
}   
复制代码

判断WiFi是否已连接:

复制代码
/** 
 * make true current connect service is wifi 
 * @param mContext 
 * @return 
 */  
private static boolean isWifi(Context mContext) {  
    ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);  
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();  
    if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {  
        return true;  
    }  
    return false;  
}  
复制代码

判断WiFi和移动流量是否已连接:

复制代码
public static boolean checkNetworkConnection(Context context)  
   {  
       final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  
       final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);  
       final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);  
  
       if(wifi.isAvailable()||mobile.isAvailable())  //getState()方法是查询是否连接了数据网络  
           return true;  
       else  
           return false;  
   }  
复制代码

只判断移动网络连接是否正常:

复制代码
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);    
    NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);   //获取移动网络信息  
    if (mMobileNetworkInfo != null) {    
        return mMobileNetworkInfo.isAvailable();    //getState()方法是查询是否连接了数据网络  
    }    
}    
return false;    
复制代码

一个工具类:

复制代码
import java.net.InetAddress;  
import java.net.NetworkInterface;  
import java.net.SocketException;  
import java.util.Enumeration;  
  
import android.app.AlertDialog;  
import android.content.Context;  
import android.content.DialogInterface;  
import android.content.Intent;  
import android.net.ConnectivityManager;  
import android.net.NetworkInfo;  
import android.net.wifi.WifiInfo;  
import android.net.wifi.WifiManager;  
import android.provider.Settings;  
import android.telephony.TelephonyManager;  
import android.util.Log;  
  
public class NetWorkUtils {  
      
//  Context context;  
    public static boolean isNetWorkAvaliable(Context context){  
          
        ConnectivityManager connect = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        if(connect == null){  
            return false;  
        }else{  
            NetworkInfo[] info = connect.getAllNetworkInfo();  
            if(info != null){  
                for(int i=0;i){  
                    if(info[i].getState() == NetworkInfo.State.CONNECTED){  
                        //网络可用  
                        return true;  
                    }  
                }  
            }  
        }  
        return false;  
    }  
      
    public static void setNetwork(final Context context){  
        AlertDialog.Builder builder = new AlertDialog.Builder(context);  
        builder.setIcon(android.R.drawable.ic_dialog_alert);  
        builder.setTitle("当前无网络连接,是否进行设置?");  
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {  
              
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
//              Intent mintent = new Intent();  
//              ComponentName comp = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");  
//              mintent.setComponent(comp);  
//              mintent.setAction("android.intent.action.VIEW");  
//              startActivity(mintent);  
                context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));  
                  
                  
            }  
        });  
        builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {  
              
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
                dialog.cancel();  
            }  
        });  
        builder.create();  
        builder.show();   
    }  
      
      
    public static String getIpAddress(Context context) {  
          
        ConnectivityManager connect = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        //检查网络连接     
        NetworkInfo info = connect.getActiveNetworkInfo();   
          
        int netType = info.getType();   
        int netSubtype = info.getSubtype();   
  
        if (netType == ConnectivityManager.TYPE_WIFI) {  //WIFI  
            return getWifiIpAddress(context);  
        } else if (netType == ConnectivityManager.TYPE_MOBILE ) {   //MOBILE  
            return getLocalIpAddress();  
        } else {   
           return "127.0.0.1";   
        }     
    }  
      
    //使用wifi  
    public static String getWifiIpAddress(Context context) {  
          
        //获取wifi服务  
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
        //判断wifi是否开启    
 //             if (!wifiManager.isWifiEnabled()) {    
 //             wifiManager.setWifiEnabled(true);      
 //             }  
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
        int ipAddress = wifiInfo.getIpAddress();  
        String ip = intToIp(ipAddress);  
        return ip;  
    }  
      
    private static String intToIp(int i) {  
        return (i & 0xFF ) + "." +  
        ((i >> 8 ) & 0xFF) + "." +  
        ((i >> 16 ) & 0xFF) + "." +  
        ( i >> 24 & 0xFF) ;  
    }  
      
    //使用GPRS  
    public static String getLocalIpAddress() {  
        try {  
            for (Enumeration en = NetworkInterface  
                    .getNetworkInterfaces(); en.hasMoreElements();) {  
                NetworkInterface intf = en.nextElement();  
                for (Enumeration enumIpAddr = intf  
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {  
                    InetAddress inetAddress = enumIpAddr.nextElement();  
                    if (!inetAddress.isLoopbackAddress()) {  
                        return inetAddress.getHostAddress().toString();  
                    }  
                }  
            }  
        } catch (SocketException ex) {  
            Log.e("Exception", ex.toString());  
        }  
        return "127.0.0.1";  
    }  
  
}  
复制代码

你可能感兴趣的:(android)