The better pattern is to create a standalone BroadcastReceiver
. This insures that your app can respond to the broadcast, whether or not the Service
is running. In fact, using this pattern may remove the need for a constant-running Service
altogether.
Register the BroadcastReceiver
in your Manifest, and create a separate class/file for it.
Eg:
<receiver android:name=".FooReceiver" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
When the receiver runs, you simply pass an Intent
(Bundle
) to the Service
, and respond to it in onStartCommand()
.
Eg:
public class FooReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do your work quickly!
// then call context.startService();
}
}