views:

62

answers:

1

I've a local service that is started in my main activity. The service is responsible for network I/O. It also interacts with other activities in my application. Till, now the service was only "providing" data to activity (using callbacks and not Intents.)

Now I need to send data (custom objects) from my activities to the service. I understand one way to do it using Intents. I know it is possible to receive an Intent in the service by overriding the onStartCommand() in my service. But it's not clear to me if the onStartCommand will be invoked every time I broadcast an Intent from my sending activity. Can a Service also be BroadcastReceiver ? If yes - how ?

Thanks.

+1  A: 

Hi,

You can create a BroadcastReceiver object in the service and register it to listen to any broadcast event you want. It's something like this:

BroadcastReceiver mScreenStateReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        //handle the broadcast event here
    }
};

@Override
public void onCreate() {
    super.onCreate();

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mScreenStateReceiver, filter);

}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mScreenStateReceiver);
}

Regards,

Bino