/** * 声明连接管理器对象 */ 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(); } }