我有一个 Activity A,它有一个进度条和一个 TextView 。
如果用户单击正在启动服务(ServiceB)的按钮,我试图找到一种方法如何从 ServiceB 更新 Activity A 中的进度条,同时在 Textview 中设置(进度)文本 Activity A.
我在 Google 和 Stackoverflow 上四处查看,我想我找到了一种方法,如描述的那样 here
但我在实现时遇到困难,非常感谢任何帮助。
PS:不要投反对票,我知道不应该直接从服务访问 UI,所以我正在寻找一种正确的方法。
一些相关代码:
Activity 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);
}
}
...
}
最佳答案
你需要使用LocalBroadcastManager 以下是需要注意的步骤
在 Activity 中创建一个 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"));
}
};
在activity的onCreate()上注册
LocalBroadcastManager.getInstance(this).registerReceiver(mLocalBroadcast ,
new IntentFilter("myBroadcast"));
在 Activity 的 onDestroy() 中注销
//取消注册,因为 Activity 即将关闭。 LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBroadcast);
将更新从服务发送到 Activity 以更新 UI
从 IntentService 通过 intent 发送进度和 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);
它将这些数据发送到我们在 Activity 中注册的mLocalBroadcast
希望这些对你有帮助。
关于android - 从服务更新/访问 Progressbar、TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42770255/