Android 网络状态操作

  /**
     * 声明连接管理器对象
     */
    private ConnectivityManager connectivityManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       //1.通过系统服务得到连接管理器对象
        this.connectivityManager= (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

       //2.通过连接管理器对象得到网络信息对象
        NetworkInfo networkInfo=this.connectivityManager.getActiveNetworkInfo();
       if(networkInfo==null) {
           Toast.makeText(this, "当前手机没有联网!", Toast.LENGTH_SHORT).show();
       }else{
           String typeName=networkInfo.getTypeName();
           System.out.println("typeName="+typeName);
           Toast.makeText(this, "typeName="+typeName, Toast.LENGTH_SHORT).show();
       }
    }

  2.

    /**
     * 声明连接管理器对象
     */
    private ConnectivityManager connectivityManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       //1.通过系统服务得到连接管理器对象
        this.connectivityManager= (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

       //2.通过连接管理器对象得到网络信息对象
        NetworkInfo networkInfo=this.connectivityManager.getActiveNetworkInfo();
        if(networkInfo.isAvailable()) {
            Toast.makeText(this, "有网络!", Toast.LENGTH_SHORT).show();
            //得到网络类型
           int type= networkInfo.getType();
            switch (type){
                //移动网络
                case ConnectivityManager.TYPE_MOBILE:
                    System.out.println("移动网络");
                    break;
                //WIFI网络
                case ConnectivityManager.TYPE_WIFI:
                    System.out.println("WIFI网络");
                    break;
            }
        }else {
            Toast.makeText(this, "没有网络", Toast.LENGTH_SHORT).show();
        }

    }

  

posted @ 2016-01-13 11:35  呼啦啦,,啦啦呼呼  阅读(197)  评论(0编辑  收藏  举报