Android:扫描Wifi网络+可选列表

时间:2013-06-18 10:54:19

标签: android android-listview wifi

我正在尝试创建一个应用程序,让您扫描可用的wifi网络,然后将它们显示在可选择的列表中。为此,我尝试使用此代码:

package android.nacho.WifiScan;

import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class WifiScan extends Activity {
    TextView mainText;
    WifiManager mainWifi;
    WifiReceiver receiverWifi;
    List<ScanResult> wifiList;
    StringBuilder sb = new StringBuilder();
    ListView listView = new ListView(this);
    ArrayAdapter<String> adapter;
    Context context = this;

    static String[] NETWORKS;

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_wifi_scan);
       mainText = (TextView) findViewById(R.id.text);
       mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
       receiverWifi = new WifiReceiver();
       registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
       mainWifi.startScan();
       mainText.setText("\\nStarting Scan...\\n");


    }

    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "Refresh");
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        mainWifi.startScan();
        mainText.setText("Starting Scan");
        return super.onMenuItemSelected(featureId, item);
    }

    protected void onPause() {
        unregisterReceiver(receiverWifi);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {


            wifiList = mainWifi.getScanResults();
            NETWORKS = new String[wifiList.size()];
            for(int i = 0; i < wifiList.size(); i++){

                NETWORKS[i]=i+"-"+(wifiList.get(i)).toString();


            }


            System.out.println("debería imprimir: "+NETWORKS[2]);


            adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_multiple_choice, NETWORKS);
            // adapter.setDropDownViewResource(android.R.layout.select_dialog_multichoice);
            listView.setAdapter(adapter);
            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            listView.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {


                }

            });

            setContentView(listView);

        }
    }
}

但我收到了这个错误:

06-18 12:36:32.670: W/dalvikvm(15499): threadid=1: thread exiting with
uncaught exception (group=0x40dfb930)

06-18 12:36:32.670: E/AndroidRuntime(15499): FATAL EXCEPTION: main

 06-18 12:36:32.670: E/AndroidRuntime(15499):
java.lang.RuntimeException: Unable to instantiate activity
 ComponentInfo{android.nacho.WifiScan/android.nacho.WifiScan.WifiScan}:
 java.lang.NullPointerException

 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)

 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)

 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
 06-18 12:36:32.670: D/AndroidRuntime(15499): Shutting down VM 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 android.os.Looper.loop(Looper.java:137) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.app.ActivityThread.main(ActivityThread.java:5039) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 java.lang.reflect.Method.invokeNative(Native Method) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 java.lang.reflect.Method.invoke(Method.java:511) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 dalvik.system.NativeStart.main(Native Method) 06-18 12:36:32.670:
 E/AndroidRuntime(15499): Caused by: java.lang.NullPointerException
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.content.ContextWrapper.getResources(ContextWrapper.java:89)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.view.View.<init>(View.java:3224) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at android.view.View.<init>(View.java:3279)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.view.ViewGroup.<init>(ViewGroup.java:431) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.widget.AdapterView.<init>(AdapterView.java:235) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 android.widget.AbsListView.<init>(AbsListView.java:766) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 android.widget.ListView.<init>(ListView.java:143) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.widget.ListView.<init>(ListView.java:139) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.widget.ListView.<init>(ListView.java:135) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.nacho.WifiScan.WifiScan.<init>(WifiScan.java:27) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 java.lang.Class.newInstanceImpl(Native Method) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 java.lang.Class.newInstance(Class.java:1319) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.app.Instrumentation.newActivity(Instrumentation.java:1054)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   ... 11 more

我做错了什么?

2 个答案:

答案 0 :(得分:16)

请尝试下面的一个。运作良好,但未经过适当测试。请自行优化代码。

public class MainActivity extends Activity {


    WifiManager mainWifi;
    WifiReceiver receiverWifi;

    StringBuilder sb = new StringBuilder();

    private final Handler handler = new Handler();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


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

        receiverWifi = new WifiReceiver();
        registerReceiver(receiverWifi, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        if (mainWifi.isWifiEnabled() == false) {
            mainWifi.setWifiEnabled(true);
        }


        doInback();
    }

    public void doInback() {
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                if (receiveWifi == null)
                    receiverWifi = new WifiReceiver();
                registerReceiver(receiverWifi, new IntentFilter(
                        WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
                mainWifi.startScan();
                doInback();
            }
        }, 1000);

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "Refresh");
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        mainWifi.startScan();

        return super.onMenuItemSelected(featureId, item);
    }


    @Override
    protected void onPause() {
        unregisterReceiver(receiverWifi);
        super.onPause();
    }

    @Override
    protected void onResume() {
        registerReceiver(receiverWifi, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {

            ArrayList<String> connections = new ArrayList<String>();
            ArrayList<Float> Signal_Strenth = new ArrayList<Float>();

            sb = new StringBuilder();
            List<ScanResult> wifiList;
            wifiList = mainWifi.getScanResults();
            for (int i = 0; i < wifiList.size(); i++) {

                connections.add(wifiList.get(i).SSID);
            }


        }
    }


}

答案 1 :(得分:3)

doInback()不会创建多个WifiReceiver,然后会以异常结束,因为它们可能都未注册?

也许s.th.像这样可以解决这个问题:

if (receiveWifi==null) {
   receiveWifi = new WifiReceiver();
}