一、判斷網路連接是否可用
public static boolean isNetworkAvailable(Context context) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (cm == null) {} else {// 如果僅僅是用來判斷網路連接 // 則可以使用 cm.getActiveNetworkInfo().isAvailable();NetworkInfo[] info = cm.getAllNetworkInfo();if (info != null) {for (int i = 0; i < info.length; i++) {if (info[i].getState() == NetworkInfo.State.CONNECTED) {return true;}}}}return false;}
下面的不僅可以判斷,如果沒有開啟網路的話,就進入到網路開啟那個介面,具體代碼如下:
protected boolean CheckNetwork() {// TODO Auto-generated method stubboolean flag = false;ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);if (cwjManager.getActiveNetworkInfo() != null)flag = cwjManager.getActiveNetworkInfo().isAvailable();if (!flag) {Builder b = new AlertDialog.Builder(this).setTitle("沒有可用的網路").setMessage("請開啟GPRS或WIFI網路串連");b.setPositiveButton("確定", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubIntent 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);}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stub dialog.cancel();}}).create();b.show();}return flag;}
用的時候可以這樣用:
if(!CheckNetwork()) return;
二、判斷GPS是否開啟
public static boolean isGpsEnabled(Context context) { LocationManager lm = ((LocationManager) context .getSystemService(Context.LOCATION_SERVICE)); List<String> accessibleProviders = lm.getProviders(true); return accessibleProviders != null && accessibleProviders.size() > 0; }
三、判斷WIFI是否開啟
public static boolean isWifiEnabled(Context context) { ConnectivityManager mgrConn = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager mgrTel = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return ((mgrConn.getActiveNetworkInfo() != null && mgrConn .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS); }
四、判斷是否是3G網路
public static boolean is3rd(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkINfo = cm.getActiveNetworkInfo(); if (networkINfo != null && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) { return true; } return false; }
五、判斷是wifi還是3g網路,使用者的體現性在這裡了,wifi就可以建議下載或者線上播放。
public static boolean isWifi(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkINfo = cm.getActiveNetworkInfo(); if (networkINfo != null && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) { return true; } return false; }