2

Disclaimer: I am fairly new to Android programming so I am trying to mimic iOS NSNotificationCenter.

I found that LocalBroadcastManager acts like NSNotifcationCenter. What I am trying to do is send a message from a static class to an activity when socket traffic finishes.

I found how to use LocalBroadcastManager from this stackoverflow answer

My question is how do I set the context('this') to my static class or I do not get the error "The method getInstance(Context) in the type LocalBroadcastManager is not applicable for the arguments (MY_STATIC_CLASS)".

LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

I am open to other way of getting this done if using LocalBroadcastManager is not the best way to send information from a static class to an activity.

Community
  • 1
  • 1
Bryan Williams
  • 693
  • 1
  • 10
  • 27

1 Answers1

5

Just pass the Context from the Activity of Application you call the static method from.

public static void sendBroadcast(Context context) { LocalBroadcastManager.getInstance(context).sendBroadcast(intent); }

From Application or Activity

StaticClass.sendBroadcast(getApplicationContext());

Or if you need to call if from static classes, pas the context on Application create.

public final class YourApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        YourClass.init(this);
    }

}


public final class YourClass {

    private static Context context;

    public static void init(Context context) {
        YourClass.context = context;
    }

    public static void sendBroadcast() {
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }

}
Yaroslav Mytkalyk
  • 16,950
  • 10
  • 72
  • 99
  • Sweet! now i can send my broadcasts from anywhere. This lines were the light from me: private static Context context; public static void init(Context context) { YourClass.context = context; } – Josh Mar 04 '15 at 14:36