在清单文件需要加上权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
下面这些代码,是封装的一个工具类,用来判断网络是否存在:
public static int getType(Context context){ int mState=-1;//-1代表无网络 //获取系统提供的服务,转换成连接管理类,这个类专门处理连接相关的东西 ConnectivityManager systemService = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); //NetworkInfo封装了网络连接的信息 NetworkInfo activeNetworkInfo = systemService.getActiveNetworkInfo(); //如果网络连接的信息等于空的话,代表无网络 if (activeNetworkInfo==null){ return mState; } int type = activeNetworkInfo.getType(); if (type==systemService.TYPE_WIFI){//代表现在是wifi网络 mState=1; }else if (type==systemService.TYPE_MOBILE){ mState=0;//代表现在是蜂窝网络 } return mState; } 下面的代码是在MainActivity里调用的:
int type = Netutils.getType(MainActivity.this); if (type!=-1){ Toast.makeText(this,"我有网咯",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this,"请检查网络",Toast.LENGTH_SHORT).show(); }