0

我正在尝试查找 Wifi 的信号强度,但我得到一个空指针异常。在获取 SSID 等网络信息时。谁能建议我一个解决方案如何删除空指针异常。

enter code here:

public class MyReciever extends BroadcastReceiver{
    WifiManager wifi;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        List<ScanResult> results=wifi.getScanResults();
        ScanResult bestSignal=null;

        for(ScanResult result:results)
        {
            if(bestSignal==null || WifiManager.compareSignalLevel(bestSignal.level, result.level)<0)
                bestSignal=result;
        }

        String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID);
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();

        Log.d("Debug","onRecieve() message:" +message);
    }

}



public class MainActivity extends Activity {

    TextView textStatus;
    WifiManager wifi;
    BroadcastReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textStatus=(TextView)findViewById(R.id.textStatus);

        wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);

        WifiInfo info=wifi.getConnectionInfo();
        textStatus.append("\n\nWifi Status: " +info.toString());

        List<WifiConfiguration> configs=wifi.getConfiguredNetworks();
        for(WifiConfiguration config:configs)
        {
            textStatus.append("\n\n" +config.toString());
        }

        if(receiver==null)
                receiver = new MyReciever();

        registerReceiver(receiver, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        Log.d("TAG", "onCreate()");
    }

    @Override
    public void onStop() {
        unregisterReceiver(receiver);
            super.onStop();
    }
    }
4

1 回答 1

1

问题可能在String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID);

当没有找到“bestSignal”时,变量“bestSignal”将为空,您正在尝试执行bestSignal.SSID这可能会导致 NPE。

更改您的代码,例如 if (bestSignal != null) { String message=String.format("%s networks found. %s is the strongest", results.size(),bestSignal.SSID); }

希望能帮助到你 :)

于 2013-10-21T10:29:23.537 回答