Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntentService - find number of Intents waiting in the queue

In my app I use an IntentService to do some work. I want to find out how many intents are waiting to be processed, as IntentService holds them in a 'work queue' , and sends the next one to onStartCommand() as the onStartCommand of the previous one has finished.

How can I find out how many Intents are waiting in this 'work queue' ?

like image 378
JonasCz Avatar asked Feb 13 '15 14:02

JonasCz


2 Answers

Actually It's quite easy: All you need to do is override onStartCommand(...) and increment a variable, and decrement it in onHandleIntent(...).

public class MyService extends IntentService {

 private int waitingIntentCount = 0;

 public MyService() {
  super("MyService");
 }

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  waitingIntentCount++;
  return super.onStartCommand(intent, flags, startId);
 }


 @Override
 public void onHandleIntent(Intent intent) {
  waitingIntentCount--;
  //do what you need to do, the waitingIntentCount variable contains
  //the number of waiting intents
 }
}
like image 93
JonasCz Avatar answered Nov 12 '22 11:11

JonasCz


Solution using SharedPreferences:

As per the documentation, the system calls onHandleIntent(Intent) when the IntentService receives a start request.

So, whenever you add an Intent to your queue, you increment and store an Integer that will represent the number of Intents in queue:

public void addIntent(){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int numOfIntents = prefs.getInt("numOfIntents", 0);
    numOfIntents++;
    SharedPreferences.Editor edit = prefs.edit();    
    edit.putInt("numOfIntents",numOfIntents);
    edit.commit();
}

Then, each time onHandleIntent(Intent) is called you decrease that Integer value:

public void removeIntent(){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int numOfIntents = prefs.getInt("numOfIntents", 0);
    numOfIntents--;
    SharedPreferences.Editor edit = prefs.edit();
    edit.putInt("numOfIntents",numOfIntents);
    edit.commit();
}

Finally, whenever you would like to check how many Intents that's in the queue, you simply fetch that value:

public void checkQueue(){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
    int numOfIntents = prefs.getInt("numOfIntents",0);
    Log.d("debug", numOfIntents);
}
like image 33
Marcus Avatar answered Nov 12 '22 10:11

Marcus