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' ?
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
}
}
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 Intent
s 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 Intent
s 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With