简体   繁体   中英

Connectivity state security issue

So I am making an app and I need to check if the user has an active internet connection. After I followed some example code on the Android Dev Resources, I am recieving an error.

It should be noted that I am using this in a fragment hence the getActivity()

Below is the method that I am using to check:

public boolean checkForConnection()
{
    Context context = getActivity().getApplicationContext();
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    return isConnected;
}

I have also declared the permissions in the manifest:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Instead of using the context

getActivity().getApplicationContext().getSystemService

try to use just the getActivity get getting the getSystemServive

ConnectivityManager cm =(ConnectivityManager)getActivity().getSystemService.getSystemService(Context.CONNECTIVITY_SERVICE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM