I have an app with :
- an activity class that allows the user to set multiple alarms.
- a service class to manage those alarms in the background.
- a receiver class to do certain work when the alarm is called.
Everything works fine.
Now I want to automatically start the service when the phone boots up. The onBootReceiver is received but the app crashes (NPE) when this line is reached in my service class:
Intent intent = new Intent (MainActivity.getContext(),AReceiver.class);
I can’t use this instead of MainActivity.getContext() either.
Any ideas of what may be causing this?
Thanks 🙂
From your code sample, it looks like the MainActivity class is not being initialized when being passed into the Intent. This means that the getContext() method will return a null value, and thats where your error is.
You need to use getContext() or getApplicationContext() from a initialized object. If this proves impossible, you could do something like this.