Skip to content Skip to sidebar Skip to footer

How Can Android Service Update The Ui Of The Activity That Started It?

I'm new to Android programming, so I'm facing some general problems about choosing the best way to design my app. What I want to do is basically a media player. I want the media pl

Solution 1:

Use an async task in your service to handle the work you need done in the background. When you need to update the UI use the progressUpdate method of async task to send a broadcast back to any interested activities.

Pseudo example.

Activity

onCreate -> startService and create new broadcastReceiver. Make sure to override the onReceive method and test for the specific intent.

    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

    broadcastReceiver = newBroadcastReceiver() {
        @OverridepublicvoidonReceive(Context context, Intent intent) {
            if(intent.getAction().equals(yourActionType)) {
                //do work here
            } 
        }
    };

onResume -> register as a broadcast receiver

    IntentFilter filter = new IntentFilter();
    filter.addAction(yourActionType);
    mLocalBroadcastManager.registerReceiver(broadcastReceiver, filter);

Service

onCreate -> create broadcast manager.

mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

onStartCommand -> create and execute a new async task if necessary. (onStart could be called multiple times)

Async Task

doInBackground -> Start whatever background task you need. In this case playing music. Make periodic calls to publishProgress

onProgressUpdate -> sendBroadcast indicating updated status

IntentbroadcastIntent=newIntent(yourActionType);
    broadcastIntent.putExtra(whateverExtraData you need to pass back);
    mLocalBroadcastManager.sendBroadcast(broadcastIntent);

onPostExecute -> sendBroadcast indicating task ended

Post a Comment for "How Can Android Service Update The Ui Of The Activity That Started It?"