ConnectivityManager is crashing while getting netw

2019-07-19 15:10发布

问题:

I am new to android and when i give the following snippet, my android application is crashing.

    ConnectivityManager manager= (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
    manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // Application is crashing in this line.

I also checked the androidmanifest.xml where i gave the internet permission to the application. Any help would be really useful for my further work.

-Thanks, Ron..

回答1:

I am not sure what you want to say but if you want to check internet connection then you can use this code

/**
     * THIS IS FUNCTION FOR CHECKING INTERNET CONNECTION
     * @return TRUE IF INTERNET IS PRESENT ELSE RETURN FALSE
     */
    public boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return (activeNetworkInfo != null && activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected());
    }

and dont forget

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


回答2:

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

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

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