Android: 如何将数据从服务传递到广播接收器

Android: How to pass data from service to broadcast reciever

在我的实验室工作中,我必须创建一个服务,当电池放电速度大于设置时发送通知。

我为该值创建了一个 Activity,带有 EditText 和用于启动和停止服务的 2 个按钮。我还创建了一个 BatteryService class,继承了 Service class 和 BatteryReciever。

现在接收者在 onStartCommand 的服务中注册操作 BATTERY_CHANGED。问题是如何将数据传递给接收者或如何了解服务中的事件。

解决这个任务的最佳方法是什么?

要触发 BroadcastReceiver,您需要使用

sendBroadcast(intent);

把你要从Service发送的数据放到intent中,如下:

Intent intent = new Intent("my.custom.action");
Bundle b = new Bundle();
b.putSerializable("name", name);
b.putShort("count", count);
intent.putExtra("bundle", b);
sendBroadcast(intent);

并在BroadcastReceiveronReceive()方法中获取数据:

@Override
public void onReceive (Context context, Intent intent){
    Bundle b = intent.getExtras();
    // do awesome things ...
}

试试这个。这会起作用。