4

I would like to setup an IntentService to fire on a timer and manually. In the case that new data is created I would like to 'manually' trigger the IntentService to send the data off immediately. The timer will just run every few minutes to ensure all data has been sent off, if it has not it will send data.

Is there a way to block/lock the IntentService such that if I am already sending data manually and the timer fires the service does not try and submit the same data twice?

I have the following IntentService which will pull an item out of the database and post that info to a server.

public class MyIntentService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
        Long id = intent.getLongExtra(SERVICE_ID, -1);
        // grab stuff out of DB based on id and submit to server
    }
}

I have a BroadcastReceiver that fires every so often to start that intent service:

public class MyBroadcastReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
       //Grab stuff I care about
       Long someId = ....;

       Intent i = new Intent(context, MyIntentService.class);
       i.putExtra(SERVICE_ID, someId);
       context.startService(i);
    }
}

And I start the broadcast receiver, to fire every 10 minutes

AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
intent = new Intent(getApplicationContext(), MyBroadcastReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 60 * 10, pendingIntent);

I fire manually elsewhere in code based on an event when I have new data to send

// On some event happened manually start intent (not on timer)
Context context = getApplicationContext();
Intent intent = new Intent(context, MyIntentService.class);
intent.putExtra(SERVICE_ID, someId);
context.startService(intent);

Again can I block somehow to ensure there are not multiple MyIntentServices running at the same time, which could be possibly sending the same data?

lostintranslation
  • 23,756
  • 50
  • 159
  • 262
  • intentservices are queued – njzk2 Aug 28 '15 at 03:36
  • @njzk2 thanks. Do multiple services get pulled off the queue at the same time. Or is it always pull one, wait until finish, pull another? – lostintranslation Aug 28 '15 at 03:38
  • 3
    `IntentService` queues its start commands and executes them serially on a background thread. Once it handles the entire queue, it stops itself. – Karakuri Aug 28 '15 at 03:41
  • a `Service` (and `IntentService`) is a singleton, they ate not queued, only `Intents` that are passed to `IntentService` via `startService` are queued – pskink Aug 28 '15 at 06:21

0 Answers0