1

我正在尝试使用 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();

是否有人可以帮助我,THX!

我已经添加了<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());
        }

    }   
}
}
4

1 回答 1

3

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 声明为类变量,而不是 call displayWifiNetworks, call handler.post(wifiRunnable);。如果您离开 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();
    }
}
于 2013-06-08T14:51:01.577 回答