In order to get the WiFi State changes, need to register a broadcast receiver. I registered a broadcast receiver in the Service like below and it all worked very well.
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.v(LOG_TAG,"Network connection sensor is starting");
//start the wifi sensor right now
mWifiReceiver = new WifiReceiver();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(mWifiReceiver, mIntentFilter);
return START_REDELIVER_INTENT;
}
private class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.v("WifiReceiver", "onReceive() is calleld with " + intent);
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
notifyScanResult();
} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
mWifiNetworkInfo =
(NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
Log.v(LOG_TAG, "mWifiNetworkInfo: " + mWifiNetworkInfo.toString());
if (mWifiNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
mBssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);
Log.v(LOG_TAG,"Connected SSID is :"+mBssid);
WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String bssid2 = info.getBSSID();
Log.v(LOG_TAG,"connected SSID "+info.getSSID());
Log.v(LOG_TAG,"Connected SSID bssid2 :"+bssid2);
AppUtils.infoLog("Connected SSID:"+info.getSSID()+":BSSID :"+bssid2+":bSSID :"+mBssid);
notifyWifiState();
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
notifyWifiState();
}
else {
return;
}
}
}
References:
http://alvinalexander.com/java/jwarehouse/android/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java.shtml
No comments:
Post a Comment