I saw this code for scanning WIFI network on this site: http://www.androidsnippets.com/scan-for-wireless-networks.
I implemented the code in the website. It works fine, but when I put the BroadcastReceiver
in an external class and call it in my activity, my log but always giving nullpointer.
I'm calling the BroadcastReceiver
in the onCreate
method called by wifiReceiver.getWifiManager.startScan()
, so basically it should start the onReceive
method from my receiver. Maybe I am wrong. Then, I call wifiReceiver.getListResult
, iterate it to output.
My question is: what am I doing wrong? Is there a right way to do it? I searched over the web and I saw people doing it in different ways, like:
nested inside a class
this way
BroacastReceiver receiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
do something
}
};
- or create a external class and call it
My simple test to see if it work this is my BroadcastReceiver
class:
public class WifiReceiver extends BroadcastReceiver {
private List<ScanResult> wifiList;
private WifiManager mainWifi;
public void onReceive(Context c, Intent intent) {
mainWifi = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
wifiList = mainWifi.getScanResults();
}
public List<ScanResult> getListResult(){
return wifiList;
}
public WifiManager getWifiManager(){
return mainWifi;
}
}
In the manifest file, I already declared my receiver and gave permissions:
<receiver android:name=".WifiReceiver">
<intent-filter>
<action android:name="android.net.wifi.SCAN_RESULTS" />
</intent-filter>
</receiver>
And the instantiation of my activity:
WifiReceiver wifiReceiver = new WifiReceiver();