BSprague
BSprague

Reputation: 5

Starting a Service from a BroadcastReceiver

The parts of this application in question are an IntentService (DatabaseService) and an AppWidgetProvider (LotWidget). In LotWidget, when a button is pressed, a PendingIntent is fired which sends a broadcast to itself, and is received in onReceive(). All of this works fine so far. In onReceive, I read the action from the Intent as well as the various extras, and either start this IntentService, or start the main Activity. Starting the activity works fine, but for some reason I can't understand, the DatabaseService isn't being started. I know code leading up to the DatabaseService intent is being sent by testing with Log.

Here is the onReceive code:

@Override
public void onReceive(Context context, Intent intent) {     
    super.onReceive(context, intent);
    if(intent.getAction().equals(RETURN_DATA_WIDGET) && initialize(context)){
        updateWidget(context);
    }
    else if(intent.getAction().equals(INTERNAL_INC)){
        Log.d("WIDG", "Incrememnt");
        Intent incr = new Intent(context, DatabaseService.class);
        incr.setAction(INCREMENT);
        incr.putExtra("incval", intent.getIntExtra("incval", 999));
        context.startService(intent);
    }
    else if(intent.getAction().equals(INTERNAL_UP)){
        Log.d("WIDG", "UPDATE");
        Intent upd = new Intent(context, DatabaseService.class);
        upd.setAction(UPDATE_COUNT);
        context.startService(intent);
    }
    else if(intent.getAction().equals(OPEN_APP)){
        Intent open = new Intent(context, TheLotActivity.class);
        open.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(open);
    }
}

Using the same intents to start the DatabaseService from the main Activity works fine. My manifest defines the DatabaseService as a Service like so:

<service android:name="com.bsprague.thelot.DatabaseService" >
    </service>

I know the Service isn't being started because a Log at the very beginning of onHandleIntent isn't being displayed, though it displays fine when this Intent is sent from the main Activity. Is there something in Android that I'm missing that makes it so you can't start a Service from a BroadcastReceiver?

Upvotes: 0

Views: 1004

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007544

You are setting an action on the Intent, and your <intent-filter> does not have that action. You might consider replacing the setAction() calls with putExtra() calls instead.

Never mind -- as you pointed out in a comment, since you are specifying the component, all other routing elements (e.g., action) are ignored. Your error from your updated comment suggests that your Intent is picking up the wrong component, LotWidget instead of DatabaseService.

Upvotes: 1

Related Questions