我的目标是创建一种从广播接收器获取数据的方法。
我有一项服务,注册一个BroadcastReceiver来监控电池插头和拔出电源插头。如何从BroadcastReceiver获取数据?我想在此服务类中接收数据:
服务:
public class myService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceivers();
return START_NOT_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private synchronized void registerReceivers() {
IntentFilter chargeFilter = new IntentFilter( Intent.ACTION_POWER_CONNECTED );
chargeFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(eCharge, chargeFilter);
}
}
这是接收者:
public class EventCharge extends BroadcastReceiver {
private static String TAG = "Event Charge";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
String messagge = "PS: " + ((action == Intent.ACTION_POWER_CONNECTED) ? "C" : "D") + " [ usb: " + usbCharge + " ac: " + acCharge + " ]";
Log.e(TAG, messagge );
}
}
有解决方案吗?
答案 0 :(得分:0)
在接收器中,您可以将所有参数放入Bundle,并使用包含该bundle的startService(Intent)来调用目标服务。在服务中,您解析捆绑并获取所有参数。
答案 1 :(得分:0)
在广播接收器中,
Intent intent = new Intent(Constants.BROADCAST_DETECTED_ACTIVITY);
// Data you need to pass to activity
intent.putExtra("type",Type);
context.sendBroadcast(intent);
在使用中,
registerReceiver(broadcastReceiver, new IntentFilter(Constants.BROADCAST_DETECTED_ACTIVITY));
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BROADCAST_DETECTED_ACTIVITY)) {
int type = intent.getIntExtra("type", 0);
}
}
};