Question

I have a IntentService that updates a global variabel in a extended Application class. In several of mine Activities I need to know when the variable is changed. Do I have to implement a BroadcastReceiver in all my Activities(and send a intent from my service) or is there a simpler way to notify my activities?

Thank you!

Was it helpful?

Solution

Yes, BroadcastReceivers were designed for just this. That said, why not just make a single parent class which has a BroadcastReceiver and all the associated logic? Then the only thing your other activities have to do is simply inherit from that parent class.

Note that you should also set some sort of global variable in persistent storage (like a shared preference) every time you send our a Broadcast. That way, if one of your activities isn't in the foreground when the Broadcast is sent, it can check the variable in persistent storage when it comes back in the onResume() method and act accordingly.

OTHER TIPS

I have also faced this type of problem. Broadcast receiver in one of the Solution. But i am not satisfied with that.So, I tried with another metod.You can find more details in object observer pattern in andrdoid,refer this link.

public class TestActivity extends Activity implements Observer {
        BaseApp myBase;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            myBase = (BaseApp) getApplication();
            myBase.getObserver().addObserver(this);
            myBase.getObserver().setValue(10);

        }

        @Override
        public void update(Observable observable, Object data) {
            // This method is notified after data changes.

            Toast.makeText(this, "I am notified" + myBase.getObserver().getValue(),
                    0).show();
        }
    }



    public class Test extends Observable
    {

        private int value=2;

        /**
         * @return the value
         */
        public int getValue() 
        {
            return value;
        }

        /**
         * @param value
         *            the value to set
         */
        public void setValue(int value) 
        {
            this.value = value;
            setChanged();
            notifyObservers();
        }
    }

    package app.tabsample;

    import android.app.Application;

    public class BaseApp extends Application {
        Test mTest;

        @Override
        public void onCreate() {
            super.onCreate();

            mTest = new Test();
        }

        public Test getObserver() {
            return mTest;
        }

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top