【发布时间】:2017-03-13 17:52:11
【问题描述】:
我有一个活动 A,它有一个进度条和一个文本视图。
如果用户单击正在启动服务的按钮(ServiceB),我正在尝试找到一种方法如何从 ServiceB 更新 Activity A 中的进度条,同时在 Textview 中设置(进度)文本活动 A。
我在 Google 和 Stackoverflow 上环顾四周,我想我找到了一种方法,如 here 所述
但我很难实现这一点,非常感谢任何帮助。
PS:不要投反对票,我知道 UI 不应该直接从服务访问,所以我正在寻找一种正确的方法。
一些相关代码:
活动 A:
@EActivity(R.layout.downloads_activity)
public class DownloadsActivity extends BaseActivity {
@ViewById(R.id.progress_text)
TextView progresstxt;
@ViewById(R.id.progressdownload)
ProgressBar downloadprogress;
// Update Progressbar and set Text sent from ServiceB
}
服务B:
public class ServiceB extends IntentService {
...
@Override
public void onProgress(DownloadRequest request, long totalBytes, long downloadedBytes, int progress) {
int id = request.getDownloadId();
if (!isActive) {
downloadManager.cancel(downloadId1);
deleteCancelledFile.deleteOnExit();
} else if (id == downloadId1) {
// How to update progressbar and textview of Activity A?
progresstxt.setText("Downloading: " + progress + "%" + " " + getBytesDownloaded(progress, totalBytes));
downloadprogress.setProgress(progress);
}
}
...
}
【问题讨论】:
-
使用绑定服务,如果你想改变意图服务,它将解决你的问题,否则使用 LocalBroadcastReceiver
-
嗨,你能给我一个示例代码吗? Intent 服务应该保持不变。
-
我正在回答,请稍候
-
好的,谢谢你的努力,我会等
-
您可以使用 LocalBroadCastManager:stackoverflow.com/questions/14695537/…