passing data from BroadcastReceiver to Service

强颜欢笑 提交于 2021-02-10 22:32:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!