Search code examples
androidservicebroadcastreceiver

Android - Starting a service with parameter from BroadcastReceiver


I wrote an application that runs a service(class MyService) when BOOT_COMPLETED received.

public class StartServiceAtBootReceiver extends BroadcastReceiver {
    public void onReceive(final Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent inten = new Intent(context, MyService.class);
            inten.putExtra("autoLogin", true);
            context.startService(inten);
        }
    }
}

This works fine. But, my problem is that I can't know how to receive the extra parameter "autoLogin" from the Service side. Normally, it can be received from onBind(Intent) method. However, it is not called in this case, because BroadcastReceiver cannot bind a service. Help me!


Solution

  • You can use

    onStartCommand(Intent intent, int flags, int startId){
        // Get parameter value here
        intent.getBooleanExtra("autoLogin",defValue);
    }