我正在尝试查找 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();
}
}