'Error In Wifi Toggle Android Code

I get this error when I press the button for the wifi toggle and the app stops working.It mentions that the user has no permission to access wifi state.The thing is its already declared in the Manifest file.

Permissions used:

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

Error

FATAL EXCEPTION: main Process: com.example.something.callblocker, PID: 935 java.lang.SecurityException: WifiService: Neither user 10052 nor current process has android.permission.ACCESS_WIFI_STATE. at android.os.Parcel.readException(Parcel.java:1472) at android.os.Parcel.readException(Parcel.java:1426) at android.net.wifi.IWifiManager$Stub$Proxy.getWifiEnabledState(IWifiManager.java:808) at android.net.wifi.WifiManager.getWifiState(WifiManager.java:1029) at android.net.wifi.WifiManager.isWifiEnabled(WifiManager.java:1041) at com.example.stamatis.callblocker.powersavings$2.onClick(powersavings.java:55) at android.view.View.performClick(View.java:4438) at android.widget.CompoundButton.performClick(CompoundButton.java:100) at android.view.View$PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method)



Solution 1:[1]

If this is happening and you are saying that android.permission.ACCESS_WIFI_STATE this is already present in manifest, then there is only one possibility that user has explicitly stopped this permission.

Check if this crash is in Marshmallow i.e API 23. Google has provided the user power to remove the permission of app explicitly.

You can read : http://www.greenbot.com/article/2990078/android/how-to-toggle-app-permissions-in-android-marshmallow.html

Only solution is to check for permission at runtime before doing toggle. This is how you can do this :

private boolean checkWriteExternalPermission()
{

    String permission = "android.permission.ACCESS_WIFI_STATE";
    int res = getContext().checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);            
}

Solution 2:[2]

Needs to be looked at by authorities for fraud and illegal activity steal the token page

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Damanpreet Singh
Solution 2 nicholas olsen