我有一个任务,该任务在Android中使用ScheduledExecutorService每30秒运行一次。它执行UI线程并正常工作。
现在我需要任务绑定服务,但是当我添加bind方法调用时,任务不会每30秒运行一次;它始终运行,并在应用程序上产生开销。
这是我任务的代码:
Runnable consumirDatosDinamicosTask = () -> {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mapContenedorDatosInstalacionesDTO != null && itemsGrillaAdapter != null) {
ContenedorInstalacionDTO datosInstalacion = mapContenedorDatosInstalacionesDTO.get(idInstalacion);
if(datosInstalacion != null){
PopuladorInstalacionGrid.popularParametrosDinamicos(instalacionGrilla, itemsGrillaAdapter,
datosInstalacion.getInversoresDTO(), datosInstalacion.getInversoresCargadoresDTO(), datosInstalacion.getReguladoresDTO());
}
}
itemsGrillaAdapter.notifyDataSetChanged();
//Here is the problem. If i uncomment bindearServicio(), the task doesn't run every 30 seconds; it runs always and It produces an overhead.
//bindearServicio();
}
});
};
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(consumirDatosDinamicosTask, 0, 30, TimeUnit.SECONDS);
void bindearServicio() {
unbindearServicio();
if (!isBinded) {
bindService(new Intent(this, InstalacionesService.class), serviceConnection, Context.BIND_AUTO_CREATE);
isBinded = true;
}
}
void unbindearServicio() {
if (isBinded) {
unbindService(serviceConnection);
isBinded = false;
}
}
有人可以帮助我看看我在做什么错吗,或者告诉我是否有更好的方法每隔30秒绑定一次服务?
预先感谢您:)