如何跟踪多个广播接收器

时间:2011-09-10 09:41:26

标签: java android broadcastreceiver

我有2个不同的文件需要初始化相同的广播接收器。我在检索结果时遇到问题。不知怎的,我偶尔会得到空值,这是因为无法正确引用启动扫描的类。

这是一个代码示例。

public void Connection_Logic (Context c)

    IntentFilter wififilter; 
    wififilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 
    public WifiManager wifiManager;
    wifireceiver = serviceConsume.wifireceiver;
    c.registerReceiver(wifireceiver, wififilter);
    wifiManager.startScan();
}

public class serviceConsume {
    public WifiManager wifiMan;
    wifiMan = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
    public BroadcastReceiver wifireceiver = new Wifi_Broadcast(this);
    IntentFilter wififilter; 
    wififilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 
    registerReceiver(wifireceiver, wififilter);
    wifiMan.startScan();
}

public class Wifi_Broadcast extends BroadcastReceiver {

    public ServiceConsume main;
    public Connection_Logic ConnLog;

    public Wifi_Broadcast(ServiceConsume main) {
        super();
        this.main = main;
    }

    public Wifi_Broadcast(Connection_Logic ConnLog) {
        super();
        this.ConnLog = ConnLog;
    }

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

        if(main != null) {
            List<ScanResults> results = ConnLog.wifiManager.getScanResults();
        } else if (ConnLog != null) {
            List<ScanResults> results = ConnLog.wifiMan.getScanResults();
        }
    }
}

有没有人有任何想法,为什么我可能会得到结果的空值?我做错了吗?如果有人有这个工作的代码示例,我们将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

if(main != null) {
            List<ScanResults> results = ConnLog.wifiManager.getScanResults();
        } else if (ConnLog != null) {
            List<ScanResults> results = main.wifiMan.getScanResults();
        }

else if中使用main,但main为null ..也许它需要看起来像这样:

   if(main != null) {
                List<ScanResults> results = main.wifiMan.getScanResults();   
            } else if (ConnLog != null) {
                List<ScanResults> results = ConnLog.wifiManager.getScanResults();
            }