如何在非Activity類中使用getSystemService()

大家好!
在繼續Activity類中使用代碼:
ConnectivityManager cm;
cm =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
即可獲取環境服務。
但,在沒有繼續Activity類中要如何使用呢?如:
public class PublicFunctions {
    public static boolean checkInternet() {
        ConnectivityManager cm;
        cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if(info != null && info.isConnected()) {
            return true;
        }else {
            return false;    
        }
    }
}
會報方法未定義錯誤,主要是要先獲取Context,再可以使用getSystemService(),但,如何獲取Context?
希望各位教招!


解決方法:

Context context;

context.getSystemService(Context.CONNECTIVITY_SERVICE);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章