Wifi扫描仪扫描多次

时间:2014-06-03 19:33:17

标签: java android android-wifi

我正在尝试创建一个应用程序,当我点击扫描按钮时会进行20次扫描,最后得到信号的平均rssi值。

我的代码如下:

MainActivity.java

package com.example.scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
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.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    WifiManager wifi;
    WifiScanReceiver wifireciever;
    WifiInfo info;
    Button scan, save;
    List<ScanResult> wifilist;
    ListView list;
    String wifis[];
    String name;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

        list=(ListView)findViewById(R.id.listView1);
        scan=(Button)findViewById(R.id.button1);
        save=(Button)findViewById(R.id.button2);


        scan.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);

                if (wifi.isWifiEnabled()==false){
                    wifi.setWifiEnabled(true);

                }

                wifireciever = new WifiScanReceiver();
                registerReceiver(wifireciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
                wifi.startScan();

            }
        });

        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                savedata();

            }
        });


    }

    public class scan_data {
        String SSID;
        String BSSID;
        int lvl;
        int count = 0;
    }


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

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

    class WifiScanReceiver extends BroadcastReceiver {
          @SuppressLint("UseValueOf")
          public void onReceive(Context c, Intent intent) {

              wifilist = wifi.getScanResults();
                 info = wifi.getConnectionInfo();
                int k = wifilist.size(); 

                 scan_data[] data = new scan_data[k];

             for (int i=0;i<20;i++){
                wifi.startScan();
                wifilist = wifi.getScanResults();

                int l = wifilist.size();

                if (i==0){
                for (int j=0;j<l;k++){
                    data[j].SSID=wifilist.get(j).SSID;
                    data[j].BSSID=wifilist.get(j).BSSID;
                    data[j].lvl=wifilist.get(j).level;
                    data[j].count++;
                }
                }




                else if (i==19){
                for (int j=0;j<l;j++){

                        if (data[j].BSSID.equals(wifilist.get(j).BSSID)){
                            data[j].lvl=data[j].lvl+wifilist.get(i).level;
                            data[j].count++;
                        }

                        data[j].lvl=data[j].lvl/data[j].count;

                        wifis = new String[l];
                         for(int r = 0; r < l; r++){
                             wifis[j]=("\n" + data[j].SSID + "\n AP Address : " +data[j].BSSID + "\n Signal Strength : " + data[j].lvl).toString();
                         }
                  }
                list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
                         android.R.layout.simple_list_item_1,wifis));
             }


                else{
                    for (int j=0;j<l;k++){
                    if (data[j].BSSID.equals(wifilist.get(j).BSSID)){
                        data[j].lvl=data[j].lvl+wifilist.get(i).level;
                        data[j].count++;
                    }
                }
             }

         }


       }
    }
    protected void savedata() {
        // TODO Auto-generated method stub
            try {
               File sdcard = Environment.getExternalStorageDirectory();
               File directory = new File(sdcard.getAbsolutePath() + "/WIFI_RESULT");
               directory.mkdirs();
               name = new SimpleDateFormat("yyyy-MM-dd HH mm ss").format(new Date());
               File file = new File(directory,name + "wifi_data.txt");

               FileOutputStream fou = new FileOutputStream(file);

               OutputStreamWriter osw = new OutputStreamWriter(fou);
               try {
                   for (int i =0; i < list.getCount(); i++){
                   osw.append(list.getItemAtPosition(i).toString());
                   }
                   osw.flush();
                   osw.close();
                   Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_LONG).show();
               } catch (IOException e){
                   e.printStackTrace();
               }
            } catch (FileNotFoundException e){
                e.printStackTrace();
            }
    }

    @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;
    }   
}

我的fragment_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/black_hd"
    tools:context="com.example.wifiscanner.MainActivity$PlaceholderFragment" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"

        android:layout_centerHorizontal="true" >
    </ListView>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/listView1"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="22dp"
        android:minWidth="@dimen/abc_action_bar_progress_bar_size"
        android:text="Scan" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/listView1"
        android:layout_alignRight="@+id/listView1"
        android:layout_marginRight="44dp"
        android:text="Save" />

</RelativeLayout>

AndriodManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.scanner"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.scanner.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>
    </application>

</manifest>

logcat的

06-04 00:59:25.940: D/dalvikvm(28589): GC_FOR_ALLOC freed 114K, 14% free 6895K/7943K, paused 26ms, total 27ms
06-04 00:59:25.970: I/dalvikvm-heap(28589): Grow heap (frag case) to 13.728MB for 6400016-byte allocation
06-04 00:59:26.150: D/dalvikvm(28589): GC_CONCURRENT freed 1K, 8% free 13144K/14215K, paused 63ms+10ms, total 181ms
06-04 00:59:26.150: D/dalvikvm(28589): WAIT_FOR_CONCURRENT_GC blocked 47ms
06-04 00:59:26.190: D/AbsListView(28589): Get MotionRecognitionManager
06-04 00:59:26.431: D/libEGL(28589): loaded /system/lib/egl/libGLES_rhea.so
06-04 00:59:26.501: D/BRCM_EGL(28589): eglCreateContext() config: 19 context: 0x4a088fb8, VC context 1, Thread 28589
06-04 00:59:26.501: D/BRCM_EGL(28589): eglCreateWindowSurface() surface: 0x4a0802f0, VC surface: 1, Thread: 28589
06-04 00:59:26.501: D/BRCM_EGL(28589): eglMakeCurrent(0x4a088fb8, 0x4a0802f0, 0x4a0802f0) Thread: 28589
06-04 00:59:26.511: D/OpenGLRenderer(28589): Enabling debug mode 0
06-04 00:59:31.035: D/AndroidRuntime(28589): Shutting down VM
06-04 00:59:31.035: W/dalvikvm(28589): threadid=1: thread exiting with uncaught exception (group=0x414f82a0)
06-04 00:59:31.075: E/AndroidRuntime(28589): FATAL EXCEPTION: main
06-04 00:59:31.075: E/AndroidRuntime(28589): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS flg=0x8000010 } in com.example.scanner.MainActivity$WifiScanReceiver@41ca4fc0
06-04 00:59:31.075: E/AndroidRuntime(28589):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:766)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at android.os.Handler.handleCallback(Handler.java:615)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at android.os.Looper.loop(Looper.java:137)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at android.app.ActivityThread.main(ActivityThread.java:4947)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at java.lang.reflect.Method.invokeNative(Native Method)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at java.lang.reflect.Method.invoke(Method.java:511)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at dalvik.system.NativeStart.main(Native Method)
06-04 00:59:31.075: E/AndroidRuntime(28589): Caused by: java.lang.NullPointerException
06-04 00:59:31.075: E/AndroidRuntime(28589):    at com.example.scanner.MainActivity$WifiScanReceiver.onReceive(MainActivity.java:119)
06-04 00:59:31.075: E/AndroidRuntime(28589):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:756)
06-04 00:59:31.075: E/AndroidRuntime(28589):    ... 9 more

我不知道错误是什么,但我觉得它在BroadcastReciever中我编码20次扫描。如果你能帮助我,我会感激你..

1 个答案:

答案 0 :(得分:0)

感谢您澄清这条线。您的问题是关于数组初始化:您初始化大小为scan_data的{​​{1}}数组,但在您在该特定命令之前说出

之前,内容仍然充满k s
null

将初始化该行。之后,您的代码将适用于该部分。

另一个可疑的事情是,您使用 data[k] = new scan_data(); 进行迭代,但每行都添加j。那不行。 AFAIK,您应该添加k++