Sim*_*mon 1 service android handler
我有一个活动 A,它有一个进度条和一个文本视图。
如果用户单击正在启动的服务(ServiceB)按钮,我试图找到一种方法如何从 ServiceB 更新 Activity A 中的进度条,同时在 Activity A 的 Textview 中设置(进度)文本。
我在 Google 和 Stackoverflow 上四处查看,我想我找到了一种方法来做到这一点,如下所述
但我在实施这一点时遇到困难,非常感谢任何帮助。
PS:不要投反对票,我知道 UI 不应该直接从服务访问,所以我正在寻找一种正确的方法。
一些相关代码:
活动一:
@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
}
Run Code Online (Sandbox Code Playgroud)
服务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);
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
您需要使用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"));
}
};
Run Code Online (Sandbox Code Playgroud)
在 Activity 的 onCreate() 上注册它
LocalBroadcastManager.getInstance(this).registerReceiver(mLocalBroadcast ,
new IntentFilter("myBroadcast"));
Run Code Online (Sandbox Code Playgroud)
在活动的 onDestroy() 中取消注册
// 由于活动即将关闭而取消注册。LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBroadcast );
将更新从服务发送到 Activity 以更新 UI
从 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);
Run Code Online (Sandbox Code Playgroud)
它将把这些数据发送到我们在 Activity 中注册的mLocalBroadcast
希望这些对你有帮助。
| 归档时间: |
|
| 查看次数: |
925 次 |
| 最近记录: |