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()){<!–要继续执行的代码–>}

    -完-

  • 相关阅读:
    IE故障修复之点击无反应
    第三十四天 我为集成平台狂(七)-步履轻盈的JQuery(五)
    《世界如此险恶,你要内心强大》读书笔记(二)
    hbase phoenix char may not be null
    堆(优先级队列) 的应用
    JVM 调优总结
    Reactor模式和NIO
    JVM调优总结 -Xms -Xmx -Xmn -Xss
    Hadoop源码分析37 RPC的线程协作
    Hadoop源码分析37 RPC的线程协作
  • 原文地址:https://www.cnblogs.com/colinliu/p/android-netcheck.html
Copyright © 2011-2022 走看看