Monday, 30 January 2012

Wifi state change


Create your own class that extends BroadcastReceiver...
public class MyNetworkMonitor extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Process the Intent here

    }
}
In AndroidManifest.xml
<receiver
    android:name=".MyNetworkMonitor" >
        <intent-filter>
            <action android:name="android.net.wifi.STATE_CHANGE" />
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />"
        </intent-filter>
</receiver>
See WIFI_STATE_CHANGED_ACTION  and CONNECTIVITY_ACTION  for an explanation of using the Intent.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////*********************************************

Check out these two pages of javadoc: ConnectivityManager  WiFiManager 
Notice that each one defines broadcast actions. If you need to learn more about registering broadcast receivers, check this out: Programmatically register a broadcast receiver
BroadcastReciever receiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifi.isWifiEnabled()==true) {
      tv.setText("You are connected");
    } else {
      tv.setText("You are NOT connected");
    }
  }
}
And in your manifest you could do something like this (if you would prefer to NOT register the receiver in code):
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <receiver android:name=".WiFiReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
        </intent-filter>
    </receiver>
</application>
+++++++++*****************+++++++++++++++++++++++++++++++++++++++++++************

Which listener does my class have to implement inorder to automatically check code if the wifi connects/disconnects ?
I'm able to manually check for wifi connection/disconnection but each time i need to connect/disconnect WIFI from android settings and then run my program for the result.
Please help. Thanx in advance.
My current code is as simple as :
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()==true)
{
    tv.setText("You are connected");
}
else
{
    tv.setText("You are NOT connected");
}

No comments:

Post a Comment