Atualizar automaticamente os serviços JmDNS em atividade
-
13-12-2019 - |
Pergunta
Estou tentando atualizar automaticamente os serviços JmDNS em segundo plano.Nada está acontecendo quando tento:
@Override
public void onDestroy() {
try {
hiNeighborService.unregisterListener(this);
this.unbindService(this.serviceConnection);
} catch (Exception ex) {
Log.e(LOG_TAG, "Exception occur during destroying the app.");
}
super.onDestroy();
}
@Override
public void onStart() {
/*new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onStart();
}
@Override
public void onRestart() {
/*new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onRestart();
}
@Override
public void onResume() {
/*new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onResume();
}
Este é o meu método resfreshServices():
private void refreshServices() {
Log.i(LOG_TAG, "Refresh available neighbors...");
final List<Neighbor> activeNeighbors = this.hiNeighborService
.getActiveNeighbors();
Log.d(LOG_TAG, activeNeighbors.size() + " active neighbors are found!");
new Thread(new Runnable() {
public void run() {
Log.i(LOG_TAG, "refresh UI...");
try {
synchronized (activeNeighborsViewModel) {
activeNeighborsViewModel.clear();
for (Neighbor neighbor : activeNeighbors) {
NeighborViewModel vm = new NeighborViewModel(
neighbor);
vm.setNeighborUnreadCount(ConnectActivity.this
.getUnreadMessageCount(neighbor));
if (activeNeighborsViewModel.contains(vm)) {
activeNeighborsViewModel.remove(vm);
}
activeNeighborsViewModel.add(vm);
}
}
notifyServiceListChanged();
Log.i(LOG_TAG, "refresh completed!");
} catch (Exception ex) {
ex.printStackTrace();
Log.e(LOG_TAG, ex.toString());
}
}
}).start();
}
Normalmente isso é chamado quando um botão é clicado, mas eu gostaria que fosse automático.Este código não faz nada a menos que eu aperte o botão Resfresh que chama resfreshServices().Tentei tentar com threads, mas a atividade fecha e o aplicativo também.Alguma ideia?
Solução
Primeiro, um pequeno comentário sobre o seu código.Por que você está implementando o mesmo código três vezes em três métodos diferentes?Presumo que você esteja programando Android (olhando para os nomes dos métodos).O método onresume é executado toda vez que a atividade é iniciada ou retomada.Ver esse link para obter mais informações sobre este tópico.
OK então...Você já verificou a documentação para obter mais informações sobre o ScheduledExecutorService?
Agora, para a questão do jmdns.A biblioteca jmDns possui uma funcionalidade integrada para atualizar os serviços.você pode ouvir novos serviços e tomar as medidas apropriadas quando novos serviços estiverem disponíveis.Não creio que a repetição de sondagens junto dos serviços seja a abordagem correcta.
Olhar aqui para um pequeno tutorial sobre como usar jmdns no Android.