在Android開發中,我們在進行網絡讀取時,常常需要先判斷手機是否聯網,如何判斷聯網呢,請參閱下面關鍵代碼:
[java]
- import android.content.Context;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
-
- public class NetHelper {
- //是否聯網網絡
- public static boolean IsHaveInternet(final Context context) {
- try {
- ConnectivityManager manger = (ConnectivityManager)
- context.getSystemService(Context.CONNECTIVITY_SERVICE);
-
- NetworkInfo info = manger.getActiveNetworkInfo();
- return (info!=null && info.isConnected());
- } catch (Exception e) {
- return false;
- }
- }
- }