【问题标题】:Update/access Progressbar, TextView from a Service从服务更新/访问进度条、TextView
【发布时间】: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/…

标签: android service handler


【解决方案1】:

您需要使用 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"));

在活动的 onDestroy() 中取消注册

// 取消注册,因为活动即将关闭。 LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBroadcast);

将更新从服务发送到活动以更新 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);

它将这些数据发送到我们在活动中注册的mLocalBroadcast

希望这些对你有所帮助。

【讨论】:

  • 很多谢谢,我只在代码中更正了这个问题'int progress = intent.getIntExtra("progress", 0);'
  • 很好,请您回答一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
相关资源
最近更新 更多