(1) 自定义工具类
public class NetWorkStateUtil {
//检查网络状态:判断网络是否可用
public static boolean isNetworkAvailable(Context context){
try{
ConnectivityManager manager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager==null){
return false;
}
else {
NetworkInfo[] networkInfo=manager.getAllNetworkInfo();
if (networkInfo!=null&&networkInfo.length>0)
{
for (int i=0;i<networkInfo.length;i++)
{
System.out.println(i+""+networkInfo[i].getState());
System.out.println(i+""+networkInfo[i].getTypeName());
if (networkInfo[i].getState()==NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}catch (Exception e){
return false;
}
}
}
(2) activity/fragment中调用
@Override
protected void onResume() {
super.onResume();
if(!NetWorkStateUtil.isNetworkAvailable(context)){
Toast.makeText(context,getString(R.string.network_connection),Toast.LENGTH_SHORT).show();
}
}
注意:最后需要在配置文件manifast中申明网络权限
<uses-permissionandroid:name="android.permission.INTERNET" />
网友评论