How to check a method as long as the app is open
For example, I want to check if wifi is enabled forever . If it is enabled my button will 开发者_运维知识库turn on, if it is off my button will turn off, but when I use my method(I will provide it) it only checks once when the app is created, but I want it to check as long as possible until the phone is turned off or the process it killed, if someone could help that would be great!
Wifi Check Method:
public void checkWifi() {
WifiManager wifim = (WifiManager) getSystemService(Context.WIFI_SERVICE);
ToggleButton wifi=(ToggleButton)findViewById(R.id.wifibutton);
if (wifim.getWifiState()==(WifiManager.WIFI_STATE_ENABLED)) {
wifi.setChecked(true);
} else {
...
}
Check the state of wifi on create, and register a broadcast receiver to listen to changes, and if WIFI goes off, change your state.
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Handle receiver
ConnectivityManager mConnectivity;
mConnectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = mConnectivity.getActiveNetworkInfo();
if (info == null || !mConnectivity.getBackgroundDataSetting()) {
//CHANGE YOUR BUTTON HERE BECAUSE THERE IS NO NETWORK AT ALL
return;
} else {
int netType = info.getType();
int netSubtype = info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
//CHANGE YOUR BUTTON HERE BECAUSE THERE IS WIFI
} else {
//CHANGE YOUR BUTTON HERE BECAUSE THERE IS NETWORK BUT ITS NOT WIFI
}
}
}
};
精彩评论