I would like to retrieve the state of the connection if it is in wifi or mobile data and this in real time, that is to say that if I desactivate the wifi or it is reactivated, I must be alerted in my widget .
I have made this code which works but is not practical at all or I have to test the connexion every second, it will reduce the battery life which is not possible.
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
// Instruct the widget manager to update the widget
Handler connexion = new Handler();
int connexiondelay = 1000; //milliseconds
connexion.postDelayed(new Runnable(){
public void run(){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
if (conn==1){
}else if (conn!=1){
conn=1;
test1.setTextViewText(R.id.con,conn+"");
appWidgetManager.updateAppWidget(appWidgetId, test1);
}
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
if (conn==2){
}else{
conn=2;
test1.setTextViewText(R.id.con,conn+"");
appWidgetManager.updateAppWidget(appWidgetId, test1);
}
}
}
connexion.postDelayed(this, connexiondelay);
}
}, connexiondelay);
I have read that it would be necessary to use broadcast but unfortunately for a week that I have been trying I can't do it, I haven't found a solution either or it doesn't work.
Thanks for your help