从服务访问值到适配器

时间:2018-08-21 09:51:36

标签: java android baseadapter android-progressbar

服务等级:

public void onNotify(TransferHandler<ProcessHolder> handler, int percentage) {
    updateprocess(percentage);
}

在适配器中

onBindViewHolder

progressBar = new ProgressBar(getContext());
progressBar = parentView.findViewById(R.id.progressbar_process);

现在我想从服务类方法访问此适配器进度的百分比

2 个答案:

答案 0 :(得分:0)

在Service类中,我写了这个

public void onNotify(TransferHandler<ProcessHolder> handler, int percentage) {
    Intent intent = new Intent("PercentageUpdates");
    intent.putExtra("percentage", percentage);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

在“活动”端,您必须接收此广播消息

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("PercentageUpdates"));

通过这种方式,您可以将百分比发送给活动。这里的mPercentageReceiver是该类中的一个类,您将执行所需的操作。...

private BroadcastReceiver mPercentageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String percentage = intent.getStringExtra("percentage");
        if (percentage != null) {
            // You can set the percentage here
        }
    }
};

答案 1 :(得分:0)

使用EventBus

按照以下步骤进行配置

1 :创建servieClass.java

public class serviceClass {

private int percentage;

public serviceClass(int percentage) {
    this.percentage = percentage;
}

public int getPercentage() {
    return percentage;
}
}

2 :更改服务

public void onNotify(TransferHandler<ProcessHolder> handler, int percentage) {
   updateprocess(percentage);
   EventBus.getDefault().post(new servieClass(percentage));
}

3 :向您的适配器添加setPercentage功能

public void setPercentage(int percentage){
    this.percentage = percentage;
    notifyDataSetChanged();
}

4 :最后将其添加到您在其中配置EventBus的片段中

 @Subscribe
public void onEvent(BlockedEvent event) {
    adapter.setPercentage(percentage);
}

祝你好运