It's the following, I'm creating app that depends on the internet connection for most services. To make it more dynamic, I thought I'd do something like the YouTube app. In the youtube app it warns you almost instantly that the application is offline. See:
IgaveageneralsearchandtriedtouseThreads
intwoways:
1.Executor+Runnable
classThreadInfinityimplementsExecutor{@Overridepublicvoidexecute(@NonNullRunnabler){while(true){r.run();}}}Threadr=newThread(newRunnable(){@Overridepublicvoidrun(){if(manager.getActiveNetworkInfo()!=null&&manager.getActiveNetworkInfo().isConnectedOrConnecting()){Toast.makeText(getApplicationContext(),"Você está conectado", Toast.LENGTH_SHORT);
} else {
Toast.makeText(getApplicationContext(), "Você está desconectado", Toast.LENGTH_SHORT);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
ThreadInfinity t = new ThreadInfinity();
t.execute(r);
2. AsyncTask
Context context = getApplicationContext();
final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
class TheadInfinity extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
while (true)
try {
if (manager.getActiveNetworkInfo() != null && manager.getActiveNetworkInfo().isConnectedOrConnecting()) {
Toast.makeText(getApplicationContext(), "Você está conectado", Toast.LENGTH_SHORT);
} else {
Toast.makeText(getApplicationContext(), "Você está desconectado", Toast.LENGTH_SHORT);
}
Thread.sleep(1000);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Erro", Toast.LENGTH_SHORT);
}
}
}
TheadInfinity t = new TheadInfinity();
t.doInBackground();
Both do not crash the app but the screen goes blank. So:
IthinkthecorrectmodeisnotwithThread.Theremustbesomelistenerthatcanbeused.ButIfoundnowhere"on the internet".
Doubt
How can I do this? =)