Friday, January 21, 2011

Detect Wifi ON/OFF state

To detect Android Wifi ON/OFF (Enable/Disable) state, we can implement a BroadcastReceiver to register with the intent WifiManager.WIFI_STATE_CHANGED_ACTION. IN the BroadcastReceiver, the Wifi state can be retrieved using the code intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN).

Detect Wifi ON/OFF state

package com.exercise.AndroidWifiStateChangedDetect;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidWifiStateChangedDetect extends Activity {

TextView WifiState;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WifiState = (TextView)findViewById(R.id.wifistate);

this.registerReceiver(this.WifiStateChangedReceiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
}

private BroadcastReceiver WifiStateChangedReceiver
= new BroadcastReceiver(){

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE ,
WifiManager.WIFI_STATE_UNKNOWN);

switch(extraWifiState){
case WifiManager.WIFI_STATE_DISABLED:
WifiState.setText("WIFI STATE DISABLED");
break;
case WifiManager.WIFI_STATE_DISABLING:
WifiState.setText("WIFI STATE DISABLING");
break;
case WifiManager.WIFI_STATE_ENABLED:
WifiState.setText("WIFI STATE ENABLED");
break;
case WifiManager.WIFI_STATE_ENABLING:
WifiState.setText("WIFI STATE ENABLING");
break;
case WifiManager.WIFI_STATE_UNKNOWN:
WifiState.setText("WIFI STATE UNKNOWN");
break;
}

}};
}


Download the files.

Related:
- Get Wifi IP of Android device, using WifiManager
- Monitor Wifi status and information with BroadcastReceiver
- Check RSSI by monitoring of WifiManager.RSSI_CHANGED_ACTION
- Turn Wifi On/Off using WifiManager.setWifiEnabled()

1 comment:

girish ghoda said...

hi,nice tutorial but i want to set text when perfactly enable wifi not when enabling