Fragment中CONNECTIVITY_SERVICE的上下文是什么,我也检查了getActivity,但它给出了错误。
public boolean isOnline() {
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (connectionManager.getActiveNetworkInfo().isConnected()) {
Log.d("ConStatus", "Data Connection On");
return true;
} else {
Log.d("ConStatus", "Data Connection off");
return false;
}
} catch (NullPointerException e) {
Log.i("ConStatus", "No Active Connection");
return false;
}
}
答案 0 :(得分:3)
getSystemService()
是Context
上的一种方法。 Fragment
会使用getActivity()
调用它:
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);