在您的服务中使用异步任务来处理您在后台完成的工作。当您需要更新UI时,请使用异步任务的progressUpdate方法将广播发送回任何感兴趣的活动。
伪示例。
活动
的onCreate - > startService和创造新的广播接收器。确保覆盖onReceive方法并测试特定的意图。
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(yourActionType)) {
//do work here
}
}
};
的onResume - >登记为广播接收机
IntentFilter filter = new IntentFilter();
filter.addAction(yourActionType);
mLocalBroadcastManager.registerReceiver(broadcastReceiver, filter);
服务
的onCreate - >创建的广播管理器。
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
onStartCommand - >根据需要创建并执行新的异步任务。 (在onStart可以多次调用)
异步任务
doInBackground - >启动你需要的任何后台任务。在这种情况下播放音乐。 做定期调用publishProgress
onProgressUpdate - > sendBroadcast显示更新的状态
Intent broadcastIntent = new Intent(yourActionType);
broadcastIntent.putExtra(whateverExtraData you need to pass back);
mLocalBroadcastManager.sendBroadcast(broadcastIntent);
onPostExecute - > sendBroadcast表明任务结束
非常感谢。但是广播消息呢?他们不是不方便在当地使用吗? – super
@super我编辑了我的答案,包括如何使用本地广播的例子。如果您的目标是旧版api版本,请确保在您的库中包含android-support-v4.jar。 – Mike
非常感谢。我会让你知道它是如何去的;) – super