问题
My goal is to create a method that gets the data from broadcast receiver.
I have a service that register a BroadcastReceiver to monitor battery plug and unplug. How can i get data from BroadcastReceiver ? I want to receive data in this service class:
Service:
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);
}
}
And this is the receiver:
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 );
}
}
Is there a solution?
回答1:
In receiver, you can just put all params into a Bundle, and use startService(Intent) containing that bundle to call the target service. In service, you parse the bundle and get all params.
回答2:
In broadcast receiver,
Intent intent = new Intent(Constants.BROADCAST_DETECTED_ACTIVITY);
// Data you need to pass to activity
intent.putExtra("type",Type);
context.sendBroadcast(intent);
In Service,
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);
}
}
};
来源:https://stackoverflow.com/questions/34657302/passing-data-from-broadcastreceiver-to-service