How to notify an activity about changes to a global variable in the application?

I have an IntentService that updates a global variable in an extended Application class. In several of my actions, I need to know when a variable changes. Do I have to execute BroadcastReceiver in all my actions (and dispatch intent from my service) or is there an easier way to notify my actions?

Thank!

+3


source to share


2 answers


Yes, BroadcastReceivers were designed to do just that. That said, why not just create one parent class that has a BroadcastReceiver and all the logic associated with it? Then the only thing others need to do is just inherit from that parent class.



Please note that you must also set some kind of global variable in persistent storage (for example the default) every time you send our broadcast. That way, if one of your actions is not in the foreground when broadcasting a broadcast, it can check the variable in persistent storage when it returns to the method onResume()

and acts accordingly.

+5


source


I also faced this kind of problem. Broadcast receiver in one solution. But I'm not happy with that. So, I tried with another method. You can find more details in the object observer template in andrdoid, link to 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;
        }

    }

      

+7


source







All Articles