How can Android service update the UI of the activity that started it?

半世苍凉 提交于 2019-11-30 06:47:34

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 = new BroadcastReceiver() {
        @Override
        public void onReceive(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

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

onPostExecute -> sendBroadcast indicating task ended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!