Android 判断网络是否正常

来源:互联网 发布:linux rsyslog配置 编辑:程序博客网 时间:2024/05/01 03:42

1.自己写一个类,用来返回值

public class Utils {

 /**
     * 返回值 -1:没有网络  1:WIFI网络   2:net网络
     */
    public static int getNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 2;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

}


2.清单权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3.接受传回来的值,用来判断状态
 int i = Util.getNetype(MainActivity.this);        if(i==-1)        {            Toast.makeText(this,"没网",Toast.LENGTH_SHORT).show();        }else if(i==1)        {            Toast.makeText(this,"wife网络",Toast.LENGTH_SHORT).show();        }else if(i==2)        {            Toast.makeText(this,"移动网络",Toast.LENGTH_SHORT).show();        }
原创粉丝点击