zoukankan      html  css  js  c++  java
  • Android检测网络是否正常代码!

    在Android开发中,如果该应用程序需要连接网络请求,那么最好我们先做一个检测网络是否在线的判断,否则程序容易出现卡死或FC等Bug,应该判断如果手机离线则弹出提示让用户检查网络,如果正常则继续执行请求。

    Android检测网络的方法:

    在提交网络请求时执行该方法即可,如果检测到网络没有连接好,则会弹出提示框:“抱歉,目前无法连接网络。请检查您的手机网络连接!”并带有打开网络设置的按钮选项。

    private boolean goToNetWork() {
            // TODO Auto-generated method stub
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if(info == null || !info.isAvailable()){
                new AlertDialog.Builder(this).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_WIRELESS_SETTINGS);
                        }else{
                            intent = new Intent();
                            ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        startActivity(intent);
                    }
                    }).setNegativeButton("联知道了!",null).show();    
                return false;
            }
            else{
                //new AlertDialog.Builder(this).setMessage("网络正常可以使用").setPositiveButton("Ok", null).show();    
                return true;
            }

    调用方法:

    if(goToNetWork()){<!–要继续执行的代码–>}

    -完-

  • 相关阅读:
    oracle ORA01001,请求资源正忙或无效
    Flex[Embed(source='assets/error.png')]无法解析用于转换的代码错误
    正在覆盖未标记为 override 的函数
    LINUX umask详解
    C++服务器学习路线
    计算kappa系数
    umask的含义及设置
    Seurat的各种数据成员访问
    GAN训练判别器和生成器时的顺序与detach
    autograd.grad 学习
  • 原文地址:https://www.cnblogs.com/colinliu/p/android-netcheck.html
Copyright © 2011-2022 走看看