转 Android杂谈--网络状态判断

http://www.cnblogs.com/loulijun/archive/2012/02/03/2337230.html 原文地址

许多联网应用都在开始运行的时候检查当前网络状态,如果没有开启则去开启它,记录一下以前写程序时的网络检查,发现人的记忆力真是有限,总是隔段时间久忘记,所以记录下来是最好的记忆。

  我们可以在一开始启动程序的时候检查网络连接状况,如果没有开启则弹出对话框设置网络

  首先需要加入权限

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

 

检查网络状态代码如下

public boolean CheckNetworkState()
    {
        boolean flag = false;
        ConnectivityManager manager = (ConnectivityManager)getSystemService(
                Context.CONNECTIVITY_SERVICE);
        if(manager.getActiveNetworkInfo() != null)
        {
            flag = manager.getActiveNetworkInfo().isAvailable();
        }
        if(!flag)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setTitle(R.string.netstate);
            builder.setMessage(R.string.setnetwork);
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Intent mIntent = new Intent("/");
                    ComponentName comp = new ComponentName("com.android.settings",
                            "com.android.settings.WirelessSettings");
                    mIntent.setComponent(comp);
                    mIntent.setAction("android.intent.action.VIEW");
                    startActivity(mIntent);
                }
            });
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create();
            builder.show();
        }
        
        return flag;
        
    }

效果如下,用户可以点击确定来设置网络,比如启动wifi

如果希望网络连接时做一些事情的话,需要判断当前网络状态是否为true,为真则进行一些操作,否则设置网络。还可以用另外一种方式,其实差不多

 

//setnetwork
    public void setNetwork()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setTitle(R.string.netstate);
        builder.setMessage(R.string.setnetwork);
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent mIntent = new Intent("/");
                ComponentName comp = new ComponentName("com.android.settings",
                        "com.android.settings.WirelessSettings");
                mIntent.setComponent(comp);
                mIntent.setAction("android.intent.action.VIEW");
                startActivity(mIntent);
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create();
        builder.show();
    }
    
    //NETWORK
    public boolean isNetworkAvailable()
    {
        Context context = getApplicationContext();
        ConnectivityManager connect = (ConnectivityManager)context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        if(connect==null)
        {
            return false;
        }else//get all network info
        {
            NetworkInfo[] info = connect.getAllNetworkInfo();
            if(info!=null)
            {
                for(int i=0;i<info.length;i++)
                {
                    if(info[i].getState()==NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

然后通过判断如果当前状态可用则执行相关代码,不可用则设置网络

if(isNetworkAvailable())
{
相关代码
}else
{
setNetwork();
}

 

可以通过ConnectivityManager获取当前网络连接状态,通过状态值判别当前网络连接

NetworkInfo info = conMan.getActiveNetworkInfo();


      if(info !=null && info.getType() ==  ConnectivityManager.TYPE_MOBILE)
      {

       // NETWORK_TYPE_EVDO_A是电信3G

      //NETWORK_TYPE_EVDO_A是中国电信3G的getNetworkType

      //NETWORK_TYPE_CDMA电信2G是CDMA

      //移动2G卡 + CMCC + 2//type = NETWORK_TYPE_EDGE

      //联通的2G经过测试 China Unicom   1 NETWORK_TYPE_GPRS


       if(info.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS

           || info.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA
           || info.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE){
          System.out.println("mobile connected");
       }
       else{
            System.out.println("type:"+info.getSubtype());
             System.out.println("not mobile");
       }
      }else
      System.out.println("not mobile connected");

 


通过getType的值可以得到以下2g|3g网络

networktype 1~15分别为:联通2G,移动2G,电信2G,电信3G,电信3G,电信3G,联通3G,联通3G,LTE,IDEN,HSUPA,HSPA,HSPAP 

 

 

 

 

 

posted @ 2012-12-11 10:49  那些人追过的年  阅读(367)  评论(0编辑  收藏  举报