我有一个IntentService,它应该向我的服务器发送数千个Volley请求。它工作正常,速度非常快。我根据从ContentProvider获取的Cursor(getContentResolver())创建请求。
但我确实想避免请求客户端已经可用的项目。我通过调用
获得了这个项目列表List<List> savedLyrics = DatabaseHelper.getInstance(this).listMetadata();
如果该列表为空,则可以正常工作。但是,如果不是 - 那么这个方法
savedLyrics.contains(Arrays.asList(artist, title))
被调用,似乎真的让事情变慢了。
public class BatchDownloaderService extends IntentService implements Response.Listener<String>, Response.ErrorListener {
private int total = 0;
private int count = 0;
private int successCount = 0;
private RequestQueue requestQueue;
private OkHttpClient client = null;
public BatchDownloaderService() {
super("Batch Downloader Service");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_NOT_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
if (client == null)
getClient();
Uri content = intent.getExtras().getParcelable("uri");
List<List> savedLyrics = DatabaseHelper.getInstance(this).listMetadata();
Cursor cursor = /* Get My Cursor */;
if (cursor == null)
return;
total = cursor.getCount();
updateProgress();
final Cache cache = new DiskBasedCache(getCacheDir(), 1024*1024);
final Network network = new BasicNetwork(new OkHttp3Stack(client));
requestQueue = new RequestQueue(cache, network, 8);
requestQueue.start();
while (cursor.moveToNext()) {
String artist = cursor.getString(0);
String title = cursor.getString(1);
if (artist == null || title == null || artist.isEmpty() || title.isEmpty() || savedLyrics.contains(Arrays.asList(artist, title))) {
// If the local database already contains this item (or if null), skip the request
updateProgress();
continue;
}
try {
Request request = QuickLyricAPI.getVolleyRequest(lrc, this, this, artist, title);
requestQueue.add(request);
} catch (Exception e) {
// Stuff
}
}
cursor.close();
}
private void updateProgress() {
/* Update the progressbar in the notification */
}
@Override
public void onErrorResponse(VolleyError error) {
updateProgress();
error.printStackTrace();
}
@Override
public void onResponse(String response) {
/* Stuff */
updateProgress();
}
private void getClient() {
/* Stuff */
}
}
如果我注释掉.contains()的调用,那么我看到列表为空并且一切都很顺利没有区别。
我尝试使用带有比较器的TreeSet()替换列表,但它没有使它更快。我试图使用String数组而不是Lists,它没有使它更快。我还尝试使用Countdownlatch来使它在所有请求完成之前onHandleIntent()没有完成。没用。
使用7.0
在Nextbit Robin上进行测试干杯