Tuesday, May 7, 2013

WIFI Connection in Android

Check WIFI is ON Or OFF In your android application 
First  to  add This line in Your AndroidManifest.xml
android.permission.ACCESS_NETWORK_STATE  
And then Use This Code: 
Public Boolean checkWifiConnection(){ 
ConnectivityManager connManager =   
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = 
connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {return true;}
else{return false; }}
 
  OR Next Solution
  

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).


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;
  }
 
 }};
}

 

No comments:

Post a Comment