Bryan Williams
Bryan Williams

Reputation: 693

Using LocalBroadcastManager with static class

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.

Upvotes: 2

Views: 2979

Answers (1)

Yaroslav Mytkalyk
Yaroslav Mytkalyk

Reputation: 17115

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);
    }

}

Upvotes: 5

Related Questions