IntentService - find the number of waiting times in a queue

In my application, I use IntentService to do some work. I want to know how many intentions are waiting for processing, since the IntentService stores them in the "work queue" and sends the next code onStartCommand()when the onStartCommandprevious one is completed .

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

+4
source share
2 answers

This is actually quite simple: all you have to do is override onStartCommand(...)and increase the value of the variable and decrease 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
 }
}
+6
source

SharedPreferences:

onHandleIntent(Intent), IntentService .

, , Intent , Integer, Intent :

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();
}

, onHandleIntent(Intent) , Integer:

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();
}

, , , Intent, , :

public void checkQueue(){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
    int numOfIntents = prefs.getInt("numOfIntents",0);
    Log.d("debug", numOfIntents);
}
0

All Articles