在我的应用程序中,我使用 IntentService 做一些工作。我想找出有多少意图正在等待处理,因为 IntentService 将它们保存在“工作队列”中,并在前一个完成后将下一个发送onStartCommand()
到。onStartCommand
我怎样才能找出这个“工作队列”中有多少 Intent 正在等待?
在我的应用程序中,我使用 IntentService 做一些工作。我想找出有多少意图正在等待处理,因为 IntentService 将它们保存在“工作队列”中,并在前一个完成后将下一个发送onStartCommand()
到。onStartCommand
我怎样才能找出这个“工作队列”中有多少 Intent 正在等待?
其实很简单:你需要做的就是覆盖onStartCommand(...)
和增加一个变量,然后在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
}
}
使用SharedPreferences的解决方案:
根据文档,系统onHandleIntent(Intent)
在IntentService
收到启动请求时调用。
因此,每当您将 an 添加Intent
到队列中时,您都会递增并存储Integer
将表示Intent
队列中 s 数量的 an:
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
队列中有多少 s 时,您只需获取该值:
public void checkQueue(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
int numOfIntents = prefs.getInt("numOfIntents",0);
Log.d("debug", numOfIntents);
}