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("抱歉,目前无法连接网络。\n请检查您的手机网络连接!").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()){<!–要继续执行的代码–>}

 

-完-

posted @ 2016-02-25 11:46  Colin.liu  阅读(2561)  评论(0编辑  收藏  举报