Search code examples
androidservice

How can my service change values of variables and UI textfields of my activities?


I have an application that get/send data from/to a remote DB on internet.

I need to get my application working in background mode, then i supose that i have to put all the send/get remote data in a service.....

but.... How can this service change values of variables and UI textfields of my activities?

i can't find any information about this, all the tutorials i am finding are of simple services that doesn't do something like that

can someone explain me how to do it please?


Solution

  • Use a BroadcastReceiver

    In your Activity place the following code:

    private BroadcastReceiver onBroadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context ctxt, Intent i) {
            // do stuff to the UI
        }
    };
    

    Register the receiver in your onResume():

    registerReceiver(onBroadcast, new IntentFilter("mymessage"));
    

    Be sure to unregister in onPause():

    unregisterReceiver(onBroadcast);
    

    In your Service, you can post the message to the Application, which will be heard by your Activity:

    getApplicationContext().sendBroadcast(new Intent("mymessage"));
    

    If you need to, you can add data to the Intent's bundle to pass to your Activity as well.