首先仍是用懒汉模式来创建Network这个工具对象。
其次,validNetwork的方法,用到connectivityManager和activeNetInfo这2个原生控件。
public class Network { private ConnectivityManager connectivityManager; private NetworkInfo activeNetInfo; private static Context context; // 饿汉式 private static Network instance = new Network(); private Network(){} public static Network newInstance(Context context){ context = context; return instance; } /* * check network permission whether is approved * @return Success: [String]connect successfully Failed: [String] Failed to connect */ private String message; public String validNetwork() { connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { message = "己連接網絡"; } else { message = "未連接網絡"; } return message; } }