在wifi.getScanResults()中访问结果时发生崩溃



我试图用getScanResults()显示WiFi的扫描结果。但是,当引用getScanResults的信息时,会发生崩溃。更详细地说,当添加的两行代码发生崩溃时:

if(results.size() > 0)
 Toast.makeText(this, "Networks available!", Toast.LENGTH_LONG).show(); 

和代码段如下:

public void displayWifiNetworks(WifiManager wifi, ListView listView) {
    List<ScanResult> results = wifi.getScanResults();
    if(results.size() > 0)
        Toast.makeText(this, "Networks available!", Toast.LENGTH_LONG).show();
是否有人可以帮助我,谢谢!

我添加了<receiver>标记,其中动作标记包含在mainFest.xml中。但是,它在运行时仍然崩溃,警告"appname has stopped", java文件和mainFest.xml如下所示:'

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.connectivitymanager"
android:versionCode="1"
android:versionName="1.0" >
    <uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />
<!-- add the permission to access and change the network state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- add the permission to access and change the WiFi state -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.connectivitymanager.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>    
    </activity>
    <!-- in order to access the WifiManage.getScanResults()  -->
    <receiver 
        android:name="com.example.connectivitymanager.MainActivity$WifiReceiver">
        <intent-filter>
            <action android:name="android.net.wifi.STATE_CHANGE"></action>
            <action android:name="android.net.wifi.SCAN_RESULTS"></action>
        </intent-filter>
    </receiver>
</application>

Java文件

com.example.connectivitymanager;
public class MainActivity extends Activity {
private TextView viewText;
private Switch switchWiFiState;
WifiManager wifi;//this is used in WifiReceiver
WifiReceiver receiverWifi;
List<ScanResult> wifiList;  
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //display the initial state of the WiFi
    String service = Context.CONNECTIVITY_SERVICE;
    ConnectivityManager connectivity = (ConnectivityManager)getSystemService(service);
    switchWiFiState = (Switch)findViewById(R.id.switch1);       
    if(connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
        switchWiFiState.setChecked(true);
    }
    else
        switchWiFiState.setChecked(false);
    //change the state when thumb the switch back and force 
    switchWiFiState.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //update the WiFi state by the switch
            String service = Context.WIFI_SERVICE;
            wifi = (WifiManager)getSystemService(service);
            receiverWifi = new WifiReceiver();
            registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            wifi.startScan();   //startScan 
            if(isChecked) {
                wifi.setWifiEnabled(true);
                //when the WiFi is enabled, the available networks should be listed in ListView listAvailableNetworks
                ListView listView = (ListView) findViewById(R.id.listAvailableNetworks);                    
                displayWifiNetworks(wifi, listView);
            }
            else 
                wifi.setWifiEnabled(false);
        }
    });


}
public void displayWifiNetworks(WifiManager wifi, ListView listView) {
    //Toast.makeText(this, "displaying WiFi information...", Toast.LENGTH_LONG).show(); 
    //if(null != wifi.getScanResults().get(1).SSID)
    List<ScanResult> results = wifi.getScanResults();
    if(results.size() > 0)
        Toast.makeText(this, "Networks available!", Toast.LENGTH_LONG).show();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
//when click the displayConnectState button, the state is displayed in the textView
public void displayConnectState(View view) {
    switch (view.getId()) {
    case R.id.button1:
        Toast.makeText(this, "Loading the connect info...", Toast.LENGTH_LONG).show();
        String service = Context.CONNECTIVITY_SERVICE;
        ConnectivityManager connectivity = (ConnectivityManager)getSystemService(service);
        viewText = (TextView) findViewById(R.id.textView2);
        viewText.setText(String.valueOf(connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getDetailedState()));
        break;
    }
}
class WifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(MainActivity.this, "in onReceive ...", Toast.LENGTH_LONG).show();
        StringBuilder sb = new StringBuilder();
        wifiList = wifi.getScanResults();
        for(int i = 0; i< wifiList.size(); i++) {
            System.out.println(wifiList.get(i).toString());
        }
    }   
}
}

getScanResults()可以返回null,大多数情况下,因为您没有权限

<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.SCAN_RESULTS"/>
从grepcode

/**
 * Return the results of the latest access point scan.
 * @return the list of access points found in the most recent scan.
 */
public List<ScanResult> getScanResults() {
    try {
        return mService.getScanResults();
    } catch (RemoteException e) {
        return null;
    }
}

他们的坏,服务抛出了一个RemoteException,他们只是忽略它。我建议您每隔3秒重试一次以检索结果:

将WifiManager声明为类变量,并调用handler.post(wifiRunnable);而不是displayWifiNetworks。如果你离开Activity,在onPause()中你必须调用handler.removeCallbacks(null);

Handler handler = new Handler();
Runnable wifiRunnable = new Runnable() {
    @Override
    public void run() {
        List<ScanResult> results = wifi.getScanResults();
        if (results == null) {
            handler.postDelayed(this, 3000);
            return;
        }
        handler.removeCallbacks(this);
        if(results.size() > 0)
            Toast.makeText(this, "Networks available!", Toast.LENGTH_LONG).show();
    }
}

最新更新