我有一个活动A,它有一个进度条和一个文本视图。
如果用户单击正在启动服务的按钮(ServiceB),我试图找到一种方法如何从ServiceB更新活动A中的进度条,同时在Textview中设置(进度)文本活动A.
我浏览了Google和Stackoverflow,我想我找到了一种方法,如here所述
但我很难实现这一点,我们非常感谢任何帮助。
PS:不要downvote,我知道不应该直接从服务中访问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
}
ServiceB:
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);
}
}
...
}
答案 0 :(得分:2)
您需要使用 LocalBroadcastManager 以下是需要注意的步骤
在活动中创建一个LocalBroadcastManager。
private BroadcastReceiver mLocalBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// take values from intent which contains in intent if you putted their
// here update the progress bar and textview
String message = intent.getStringExtra("message");
int progress = Integer.parseInt(intent.getStringExtra("progress"));
}
};
在活动的onCreate()
上注册 LocalBroadcastManager.getInstance(this).registerReceiver(mLocalBroadcast ,
new IntentFilter("myBroadcast"));
取消注册活动的onDestroy()
//取消注册,因为活动即将关闭。 LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBroadcast);
将更新从服务发送到活动以更新用户界面
从IntentService发送进度和textView更新通过意图
Intent intent = new Intent("myBroadcast");
// You can also include some extra data.
intent.putExtra("message", "This is my message!"); // msg for textview if needed
intent.putExtra("progress", progressValue); // progress update
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
它会将这些数据发送到我们在活动中注册的 mLocalBroadcast
希望这些可以帮助你。