Search code examples
androidbroadcastreceiverandroid-contextandroid-broadcastreceiver

Android - Getting Context from a Method called within onReceive?


How do you retrieve a context from within a Method that was called from onReceive?

Here is an Example of what I'm trying to accomplish:

@Override
public void onReceive(Context context, Intent intent) {
    ...
    ...
    if(...) {
        callMethodOne();
        callMethodTwo();
    } else if (...) {
        callMethodOne();
    }
    ...
}

private void callMethodOne() {
    // Cant use getApplicationContext
    SharedPreferences getPrefs =
      PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
}

private void callMethodTwo() {
    // Cant use getSystemService
    NotificationManager notificationManager =
      (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

As you can see, since the Methods are called multiple times/ways, moving all the code to be inside onReceive would end up being very repetitive and extremely inefficient.

Any help is greatly appreciated!
Thank you.


Solution

  • Pass it the Context:

    private void callMethodOne(Context context) {
        // Can't use getApplicationContext
        SharedPreferences getPrefs =
            PreferenceManager.getDefaultSharedPreferences(context);
    }