添加网络状态权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
代码示例:
public void checkNet(View v){ if(isNetworkConnected(this)){ Toast.makeText(this, "网络可用",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this, "网络不可用",Toast.LENGTH_SHORT).show(); } } //检查网络状态 public boolean isNetworkConnected(Context context){ if(context!=null){ ConnectivityManager mConnectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo=mConnectivityManager.getActiveNetworkInfo(); if(mNetworkInfo!=null){ return mNetworkInfo.isAvailable(); } } return false; }