我在Android的一个可用于扫描仪的项目中。扫描仪型号为Avision AN240W。
这个想法是扫描大量页面,然后将它们发送到处理它们的服务器(OCR)。 REST服务由第三方提供,因此无法修改。
我的问题是我可能在80页左右的时间后收到OutOFMemoryException。问题在于服务器排队呼叫正在等待响应。
我正在努力处理同步和异步请求,添加了Dispatcher.setMaxRequests参数,自定义调度程序以及类似的东西。但是我无法解决内存异常的问题。
也尝试了How to make a thread limit in Java ,但我总是看到请求不受限制。
我知道我做错了,但看不到。
Rertofit(客户端)服务构建器在单独的类中:
public class APIClientFC {
DECLARATIONS & INIT ATTRIBUTES: url, user, password
public static Retrofit getClient(String url, String user, String password) {
logging.setLevel(Level.HEADERS);
Dispatcher dispatcher = new Dispatcher(Executors.newFixedThreadPool(2));
dispatcher.setMaxRequests(2);
dispatcher.setMaxRequestsPerHost(1);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new BasicAuthInterceptor(user, password))
.addInterceptor(logging)
.dispatcher(dispatcher)
.connectTimeout(150, TimeUnit.SECONDS)
.writeTimeout(300,TimeUnit.SECONDS)
.readTimeout(600,TimeUnit.SECONDS).build();
if(retrofit == null) {
retrofit = new Retrofit.Builder()
.client(httpClient)
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
在单独的类中的实现调用:
public AddNewImage addNewImage() {
return APIClientFC.getClient(url, user, password).create(AddNewImage.class);
}
请求:
private void addImages() {
AddNewImage addImg = apiCallFC.addNewImage();
FileFC archivo = new FileFC();
AddNewImageIN parms = new AddNewImageIN(session.getId(), lote.getId(), archivo);
Call<AddNewImageOUT> call;
byte[] bytes = new byte[READ_SIZE + 1];
BufferedInputStream buf;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.NO_WRAP);
errorEnvio = false;
int bytesRead;
for (int numArchivo = 0; numArchivo < scanList.size() && !errorEnvio; numArchivo++) {
archivoEnviar = scanList.get(numArchivo);
try {
File file = new File(archivoEnviar);
Arrays.fill( bytes, (byte) 0 );
buf = new BufferedInputStream(new FileInputStream(file));
while ((bytesRead = buf.read(bytes)) != -1) {
output64.write(bytes, 0, bytesRead);
}
output64.close();
buf.close();
archivo.setName(file.getName());
archivo.setBytes(output.toString());
parms.getParams().setFile(archivo);
call = addImg.addNewImage(parms);
call.enqueue(new Callback<AddNewImageOUT>() {
AddNewImageOUT newImg;
@Override
public void onResponse(Call<AddNewImageOUT> call, Response<AddNewImageOUT> response) {
try {
error = true;
++sendedArchive;
if (response.isSuccessful()) {
newImg = response.body();
if (newImg == null) {
error = false;
if((sendedArchive == scanList.size())) {
//CLOSE & PROCESS
}
}
}
if (error) {
//ERROR PROCESSING
...
}
} catch (Exception e) {
//ERROR PROCESSING
...
}
}
@Override
public void onFailure(Call<AddNewImageOUT> call, Throwable t) {
//ERROR PROCESSING
...
}
});
} catch (FileNotFoundException e) {
//ERROR PROCESSING
...
} catch (IOException e) {
//ERROR PROCESSING
...
}
}
}