【Android-NetWork】 判断是否连接网络,判断网络连接方式
如何判断Android是否连接网络?
Java代码:
ConnectivityManager conn = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); boolean wifi = conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); boolean internet = conn.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); if (wifi | internet) { Toast.makeText(getApplicationContext(), "网络已连接", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "未连接网络。", Toast.LENGTH_LONG).show(); }
AndroidManifest.xml添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
================我是分割线====================
Android判断设备网络连接状态,并判断连接方式
如何判断Android设备网络连接状态,并判断连接方式?
--调用checkNetworkState方法--
ConnectivityManager manager; /*检测网络是否连接*/ private boolean checkNetworkState() { boolean flag = false; //得到网络连接信息 manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); //去进行判断网络是否连接 if (manager.getActiveNetworkInfo() != null) { flag = manager.getActiveNetworkInfo().isAvailable(); } if (!flag) { setNetwork();//设置网络 } else { isNetworkAvailable();//判断连接方式 } return flag; } /* 网络已连接,判断连接方式 */ private void isNetworkAvailable() { State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState(); State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); if (gprs == State.CONNECTED || gprs == State.CONNECTING) { Toast.makeText(this, "网络已连接!连接方式:gprs", Toast.LENGTH_SHORT).show(); } if (wifi == State.CONNECTED || wifi == State.CONNECTING) { Toast.makeText(this, "网络已连接!连接方式:wifi", Toast.LENGTH_SHORT).show(); // do something: wifi状态下才能做某事 } } /* 网络未连接,调用设置方法 */ private void setNetwork() { Toast.makeText(this, "网络未连接。", Toast.LENGTH_SHORT).show(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("网络提示信息"); builder.setMessage("网络不可用,如果继续,请先设置网络!"); builder.setPositiveButton("设置", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = null; /* * 判断手机系统,如果API>10 就是3.0+ 3.0以上和3.0以上设置不一样, 调用的方法不一样 */ if (android.os.Build.VERSION.SDK_INT > 10) { intent = new Intent(android.provider.Settings.ACTION_WIFI_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); } }); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create(); builder.show(); }