android-fragments 片段中CONNECTIVITY_SERVICE的上下文是什么?

wgmfuz8q  于 2022-11-14  发布在  Android
关注(0)|答案(2)|浏览(134)

片段中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;
    }
}
1hdlvixo

1hdlvixo1#

getSystemService()Context上的一个方法。Fragment将使用getActivity()调用它:

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
y1aodyip

y1aodyip2#

当我试图在一个片段中实现GoogleMap离线tile提供程序时,我遇到了类似的问题(基于0ne_Up的答案here)。

private ConnectivityManager connectivityManager;
...
connectivityManager = (ConnectivityManager) getActivity().
    getSystemService( getActivity().CONNECTIVITY_SERVICE );

相关问题