fragment中判断网络

private ConnectivityManager manager;
private boolean flag;



flag=GetInfo(getActivity());
if(flag){
    Toast.makeText(getActivity(),"网络已连接",Toast.LENGTH_SHORT).show();
}else{
    Toast.makeText(getActivity(),"请连接网络",Toast.LENGTH_SHORT).show();
}



public boolean GetInfo(Context context) {
    //得到网络连接信息
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    //判断网络是否连接
    if (manager.getActiveNetworkInfo()!=null){
        boolean flag=manager.getActiveNetworkInfo().isAvailable();
        if (flag){
            NetworkInfo.State state = manager.getActiveNetworkInfo().getState();
            if (state==NetworkInfo.State.CONNECTED){
                return true;
            }
        }
    }
    return false;
}


你可能感兴趣的:(fragment中判断网络)