4

Although I know there are some answers out there already, I don't quite understand them as I am just a beginner in Android programming. I tried to instantiate my receiver using the following code:

<receiver
    android:name="com.example.android.exampleapp.MainActivity$NetworkChangeReceiver"
    android:enabled="true"
    android:label="NetworkChangeReceiver">
    <intent-filter>
        <action android:name="android.net.wifi.STATE_CHANGE" />
    </intent-filter>
</receiver>

but it did not work. The logcat says:

java.lang.RuntimeException:
Unable to instantiate receiver com.example.android.exampleapp.MainActivity$NetworkChangeReceiver:
    java.lang.InstantiationException:
        class com.example.android.exampleapp.MainActivity$NetworkChangeReceiver has no zero argument constructor

Part of my code in MainActivity.java is shown below:

public class NetworkChangeReceiver extends BroadcastReceiver {
    /* All my code that reacts when WiFi state changes are here */
}

I know this question might sound easy, but I seriously do not know how to resolve this error. I had read this (which I think is kinda invalid - I do not have a empty constructor) and a bunch of other online tutorials but I still can't get it. Any help would be appreciated :)

Community
  • 1
  • 1

1 Answers1

10

Change:

public class NetworkChangeReceiver extends BroadcastReceiver

to:

public static class NetworkChangeReceiver extends BroadcastReceiver

Or, move NetworkChangeReceiver to be a public class in its own Java file.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • What if i got non-static methods in `public class NetworkChangeReceiver extends BroadcastReceiver`? –  Feb 04 '16 at 13:57
  • @YikJin: Then you cannot register it in the manifest. You would have to use `registerReceiver()` in your activity, with a side effect that your receiver will only be watching for broadcasts while the activity is around (and, IIRC, in the foreground). – CommonsWare Feb 04 '16 at 14:00