如何将值从广播接收器发送到已启动的活动

时间:2017-11-22 11:23:57

标签: android android-broadcastreceiver

我是Android开发的新手,请帮助我解决我的问题。

  1. 为了获得电池百分比,我已经完成了这个程序,并能够干杯 广播接收器中的电池百分比

  2. 我遇到的问题无法再次在主要活动中获得。

  3. 因为我的应用程序中的所有活动都需要使用广播 电池电量接收器

  4. 所以我把它保存为单独的java类文件,而不是将它保存在Activity本身。

  5. 如何将广播接收器的值发送到动态注册的主要活动以及从哪里获取电池值

  6. MainActivity

    public class MainActivity extends AppCompatActivity {
    public static final String BATTERY_BROADCAST_ACTION = Intent.ACTION_BATTERY_CHANGED;
    Context context;
    private IntentFilter mIntentFilter;
    private BroadcastReceiver myReceiver;
    TextView txtBattery;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button) findViewById(R.id.btnCall);
        txtBattery = (TextView) findViewById(R.id.txtBattery);
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, new 
        IntentFilter(BATTERY_BROADCAST_ACTION));
    }}
    

    BroadCast Receiver

    public class MyReceiver extends BroadcastReceiver {
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Bundle extras = intent.getExtras();
        int level = extras.getInt(BatteryManager.EXTRA_LEVEL);
        Toast.makeText(context,"Battery = " + level,Toast.LENGTH_SHORT).show();
    }}
    

1 个答案:

答案 0 :(得分:0)

您可以使用事件总线系统来解决您的问题。您可以使用EventBus

首先,为电池电量更改创建事件

public class BatteryLevelEvent {
  private int batteryLevel;

  public BatteryLevelEvent(int batteryLevel) {
    this.batteryLevel = batteryLevel;
  }

  public int getBatteryLevel() {
    return this.batteryLevel;
  }
}

其次,每当电池电量发生变化时,发布事件:

public class MyReceiver extends BroadcastReceiver {
  ...
  @Override
  public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();
    int level = extras.getInt(BatteryManager.EXTRA_LEVEL);
    EventBus.getDefault().post(new BatteryLevelEvent(level));
  }
}

现在,您需要接收活动。每个想要接收活动的活动都需要首先注册。您可以通过以下方式注册:

public class YourActivity extends AppCompatActivity {
  ...

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    ...
    EventBus.getDefault().register(this);
  }

  // need to unregister when activity is not in foreground.
  @Override
  public void onPause() {
   super.onPause();
   EventBus.getDefault().unregister(this);
  }
}

最后,您需要订阅才能接收活动:

public class YourActivity extends AppCompatActivity {
  ...

  @Subscribe
  public void onMessageEvent(BatteryLevelEvent event) {
    int batteryLevel = event.getBatteryLevel();
    // do something with the battery level here.
  }
}

如果您想在所有活动中收到活动,可以使用上面的注册,取消注册和订阅创建基类活动。然后,您可以从该基类派生所有活动。