I want my application to check whether mobile data is enabled
This works fine when you just click a button, but it does only refresh the information once after a click and not automatically in “real time”.
threadCheck = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
setTextfield(isMobileDataEnabled());
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
this.startbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
threadCheck.run();
}
});
Whats the best, cpu friendliest, way to make this thread “loop” ?
I tried to call isMobileDataEnabled() recursively but that ended up in an stackoverflow error.
Sincerly,
Wolfen
I think your best bet would actually be the ConnectivityManager broadcast listener. It will tell you when the network is available or not available. Register for the broadcast and in the listener update your button. This way there is no loop and your CPU remains mostly idle. When the network changes, it will notify your broadcaster without any polling necessary. It’s pretty fast so I wouldn’t worry about “real time” 😉
These should help get you started.
http://developer.android.com/reference/android/net/ConnectivityManager.html
http://developer.android.com/reference/android/content/BroadcastReceiver.html