Android 判断是否有网及无网处理

来源:互联网 发布:英国工资 知乎 编辑:程序博客网 时间:2022/07/04 22:52

当我们开发时,为了提高用户的体验,常常要监测手机的网络状态,当手机处于无网状态时,我们会做一些相应的处理或者引导用户去打开网路,以下是我总结的一些经验,不足之处,还请谅解,如果有错误的地方,欢迎拍砖.(做了快两年的Android了,总觉得要做点什么,要不然感觉自己都在虚度了)奋斗


首先我们得自定义一个NetStateReceiver 继承extends  BroadcastReceiver

public class NetStateReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        boolean isNet = NetworkUtil.isConnected();        if (isNet) {            EventBus.getDefault().post(0, ConstantValue.Net_open);        }else            EventBus.getDefault().post(1, ConstantValue.Net_open);    }}
这里我用的是org.simple.eventbus.EventBus 框架来更新事件,如果大家不熟悉可以使用广播,或者其他自己熟悉的方式:0代表现在网络是打开的,1代表没打开

当然我们还得在配置文件里面单独注册:
   <!--监听网络变化广播-->
        <receiver android:name=".common.network.NetStateReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

当然这里还需注册网络操作权限:


  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

当监测到没网时,我们可能需要引导用户去打开网络:

/*
    * 打开设置网络界面
    * */
    public static void setNetworkMethod(final Context context){
        //提示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                }else{
                    intent=new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
//                    intent = new Intent();
//                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
//                    intent.setComponent(component);
//                    intent.setAction("android.intent.action.VIEW");
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).show();
    }

当然一般我们打开一个activity的时候,可能首先会去监测是否有网:

boolean isNet = NetworkUtil.isConnected();if (!isNet) {    NetworkUtil.getInstance().setNetworkMethod(this);}
以下是NetworkUtil代码:
package com.jxhdc.aspire.jxhdcandroid.common.utils;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import com.jxhdc.aspire.jxhdcandroid.JXHDCApplication;import org.simple.eventbus.EventBus;/** * 网络工具类 * Created by chenziqiang on 16/4/21. */public class NetworkUtil {    private volatile static  NetworkUtil instance;    public NetworkUtil(){        instance=this;    }    public synchronized static NetworkUtil getInstance() {        if (instance == null) {            synchronized (NetworkUtil.class) {                instance = instance == null ? new NetworkUtil() : instance;            }        }        return instance;    }    public static boolean isConnected() {        Context context = JXHDCApplication.getContext();        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo activeInfo = manager.getActiveNetworkInfo();        if (activeInfo != null) {            return activeInfo.isConnected();        }        return false;    }//    public static boolean isNetConnected() {//        ConnectivityManager cm = (ConnectivityManager) JXHDCApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);//        NetworkInfo info = cm != null ? cm.getActiveNetworkInfo() : null;//        return info != null && info.isConnected();//    }    public static boolean isWifiConnected() {        boolean isConnected = false;        try {            ConnectivityManager cm = (ConnectivityManager) JXHDCApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);            isConnected = info.isConnected();        } catch (Exception e) {            e.printStackTrace();        }        return isConnected;    }    public static boolean isMobileConnected() {        boolean isConnected = false;        try {            ConnectivityManager cm = (ConnectivityManager) JXHDCApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);            isConnected = info.isConnected();        } catch (Exception e) {            e.printStackTrace();        }        return isConnected;    }    /*    * 打开设置网络界面    * */    AlertDialog.Builder builder=null;    public void setNetworkMethod(final Context context){        if (builder!=null){            builder.setCancelable(true);        }        //提示对话框        builder=new AlertDialog.Builder(context);        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                Intent intent=null;                //判断手机系统的版本  即API大于10 就是3.0或以上版本                if(android.os.Build.VERSION.SDK_INT>10){                    intent = new Intent(android.provider.Settings.ACTION_SETTINGS);                }else{                    intent=new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);//                    intent = new Intent();//                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");//                    intent.setComponent(component);//                    intent.setAction("android.intent.action.VIEW");                }                context.startActivity(intent);            }        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                dialog.dismiss();            }        }).show();    }    /**     * 网络异常提示界面
     */    public  void setNetworkAnomaly(final Context context){        //提示对话框        AlertDialog.Builder builder=new AlertDialog.Builder(context);        builder.setTitle("网络异常提示").setMessage("网络连接异常,请再试一次?").setPositiveButton("是", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                EventBus.getDefault().post("0","request_data");            }        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                dialog.dismiss();            }        }).show();    }}

0 0
原创粉丝点击