-2

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();
4

1 回答 1

1

有多种方法可以实例化一个类,包括您提到的所有方法。您选择哪一个取决于您要完成的任务,因此没有“最佳”选项。我尽量避免使用匿名类(您的第二个建议),因为它们不像其他选项那么明显。

当您的应用程序接收到您的接收器已为其注册的广播 Intent 时,系统会调用方法 BroadcastReceiver.onReceive。

一旦 onReceive() 完成,BroadcastReceiver 就会被销毁。你不能指望它保存它的任何状态。BroadcastReceiver 的参考文档中描述了完整的接收器生命周期。

结果,一旦 onReceive 完成,wifiList 就不再存在。

使用广播接收器接收消息并决定要做什么。不要将处理放在广播接收器中;相反,调用方法。这意味着定义广播接收器的一个不错的选择是使其成为 Activity(或 Fragment)的内部类,这允许接收器调用 Activity 或 Fragment 中的方法。

于 2013-06-12T23:00:55.907 回答