Broadcast Receiver类将状态发送到片段

时间:2017-04-01 13:26:11

标签: java android broadcastreceiver

我有一个广播接收器作为我班级的一部分,在将广播接收器移动到它自己的类时,我无法将任何类型的值返回给需要该数据的类。有没有办法设置数据,然后将其发送回已注册数据的类?

概述类应该能够获取BatteryReceiver类发布的状态。

viewModel = function(){
    var self = this;
    self.currentView = ko.observable();

    self.loadView = require(['text!views/Client1/faq.html', 'text!view/faq.html'], function(clientView, defaultView) {
        if(clientView) {
            self.currentView('views/Client1/faq.html');
        } else {
            self.currentView('view/faq.html');
        }
    });

}

BatteryReceiver类应该能够将数据发送回实现它的类。

public class Overview extends Fragment {

    private Unbinder unbinder;

    private BroadcastReceiver batteryReceiver = new BatteryReceiver();

    @BindView(R.id.bat_generic)
    TextView batText;

    public Overview() {
        // Required empty public constructor
    }

    public static Overview newInstance() {
        return new Overview();
    }

    @Override
    public void onCreate(Bundle outState) {
        super.onCreate(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_overview, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();

        try {
            initView();

            getActivity().registerReceiver(
                    batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            );

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        unbinder.unbind();
        getActivity().unregisterReceiver(batteryReceiver);
    }

    private void initView() {

        batText.setText(
          // TODO: logic  
        );
}

1 个答案:

答案 0 :(得分:1)

基本上你不能在不是上下文的类中注册广播,但有一种方法可以将上下文传递给其他类。

        // implements OnBatteryChange in your activity
    public class MainActivity extends AppCompatActivity implements OnBatteryChange {...
    // add following method in your activity
     @Override
      public void batteryChanged(String data) {
        txtBat.setText(data);
      }
    // add following line in onCreate() in activity

    OtherReceiver reciever = new OtherReceiver(getApplicationContext(),this);
    reciever.doSomethingWithReceivedIntent();

        //OtherReceiver class

        public class OtherReceiver {
    Context context;
    OnBatteryChange batteryChange;

    public OtherReceiver(Context context, OnBatteryChange batteryChange) {
        this.context = context;
        this.batteryChange = batteryChange;
    }

    public void doSomethingWithReceivedIntent() {
        BatteryReceiver batteryReceiver = new BatteryReceiver();
        batteryReceiver.setBatteryChange(batteryChange);
        context.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }
}

    //OnBatteryChange interface

    public interface OnBatteryChange {
        void batteryChanged(String data);
    }

    //amend BatteryReceiver to following code 
public class BatteryReceiver extends BroadcastReceiver {
    OnBatteryChange batteryChange;

    public void setBatteryChange(OnBatteryChange batteryChange) {
        this.batteryChange = batteryChange;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        int percentage = (int) (((float) level / (float) scale) * 100.0f);

        switch (deviceStatus) {
            case BatteryManager.BATTERY_STATUS_CHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Charging:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Discharging:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_FULL:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Full:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_UNKNOWN:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Unknown:", percentage, "%"));
                break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:

                batteryChange.batteryChanged(context.getString((R.string.bat_charge), "Not charging:", percentage, "%"));
                break;
        }
    }

}

要取消注册,您也可以定义另一种方法。