处理Android连接到扫描网络

时间:2018-01-04 09:11:01

标签: android processing

我正在尝试编写一个从扫描结果连接到特定网络的小应用程序但是我得到“全局变量networkId不存在”的错误,但是当我使用配置的网络而不是扫描结果时,相同的代码工作。

import java.util.List;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.app.Activity;

Activity act;
Context context;
WifiManager wm;
List<ScanResult> results;
WifiInfo wifiInfo;
String networkSSID = "test";
String networkPass = "testtest";


void setup() {

    size(displayWidth, displayHeight, P3D);
    act = this.getActivity();
    context = act.getApplicationContext();
}


void draw() {
    textSize(height / 18);
    textMode(CENTER);
    fill(255);
    text("hello world", width / 2, height / 2);

    if (mousePressed == true) {
        wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration conf = new WifiConfiguration();
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.preSharedKey = "\"" + networkPass + "\"";
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wifiManager.addNetwork(conf);
        List<ScanResult> result = wifiManager.getScanResults();
        for (ScanResult i : result) {
            if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                println("Disconnectting from all networks");
                wifiManager.disconnect();
                println("Connecting to " + networkSSID);
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();

                break;
            }
        }
    }
}

Update1:​​

所以我尝试了一些东西,但现在我得到一个我根本不理解的错误......

FATAL EXCEPTION: GLThread 337489
Process: processing.test.wifi_list, PID: 30539
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
    at processing.test.wifi_list.WiFi_List$WiFiList.connect(WiFi_List.java:160)
    at processing.test.wifi_list.WiFi_List.draw(WiFi_List.java:84)
    at processing.core.PApplet.handleDraw(Unknown Source)
    at processing.opengl.PSurfaceGLES$RendererGLES.onDrawFrame(Unknown Source)
    at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1548)
    at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1259)

新代码:

import java.util.List;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.app.Activity;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration;


WiFiList wifiList;
ArrayList<WiFiListItem> wifiNetworks;
int fontSize;
String message = "Tap to scan";

void setup() {
  size(displayWidth, displayHeight, P2D);
  orientation(PORTRAIT);

  wifiList = new WiFiList();
  wifiList.init();
  wifiNetworks = wifiList.getItems();

  fontSize = height/30;
  textSize(fontSize);
  textAlign(LEFT, TOP);
  noStroke();
}


void draw() {
  background(255);  

  fill(0);
  text(message, width/2, height/2);

  int currentHeight = 3 * fontSize;
  int barHeight = 5 + fontSize;

  // draw a bar representing the signal strengths for each network
  for (WiFiListItem item : wifiNetworks) {
    fill(200);
    float barWidth = map(item.level, -100, -10, 30, width);
    rect(0, currentHeight, barWidth, barHeight);
    fill(0);
    text(item.name + " : " + item.level, 10, currentHeight);
    currentHeight += barHeight;
  }
  // start scanning when the screen is tapped
  if (mousePressed == true) {

    wifiList.scan();
    wifiList.connect();
  }
}

// this function is called when the WiFiList object is done scanning
void wifiScanFinished() {
  message = "Scan Finished";
  wifiNetworks = wifiList.getItems();
}

WiFiList类

class WiFiList {
  protected WifiManager wifiManager;
  protected List<ScanResult> scanList;
  protected ArrayList<WiFiListItem> items;
  protected boolean bScanning = false;
  protected Activity act;
  protected Context context;

  WiFiList() {
    items = new ArrayList<WiFiListItem>();
  }

  boolean isScanning() {
    return bScanning;
  }

  ArrayList<WiFiListItem> getItems() {
    while (bScanning) {
    }
    return new ArrayList<WiFiListItem>(items);
  }

  void init() {
    wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);

    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

    getActivity().registerReceiver(new BroadcastReceiver() {
      public void onReceive(Context context, Intent intent) {
        println("WiFiList: scan finished");
        scanList = wifiManager.getScanResults();
        for (ScanResult networkDevice : scanList) {
          updateItem(networkDevice.SSID, networkDevice.level);
        }
        bScanning = false;
        wifiScanFinished();
      }
    }
    , filter);
  }

  void updateItem(String name, int level) {
    for (WiFiListItem item : items) {
      if (item.name.equals(name)) {
        item.level = level;
        println("[Updated] " + name + " : " + level);
        return;
      }
    }
    items.add(new WiFiListItem(name, level));
    println("[Added] " + name + " : " + level);
  }

  void scan() {
    if (bScanning) {
      println("WiFiList: already scanning");
      return;
    }
    bScanning = true;
    println("WiFiList: starting scan");
    wifiManager.startScan();
  }

  void connect() {

    wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + "test" + "\""; 
    conf.wepKeys[0] = "\"" + "testtest" + "\""; 
    conf.preSharedKey = "\""+ "testtest" +"\"";
    conf.wepTxKeyIndex = 0;
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
    wifiManager.addNetwork(conf);

    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for ( WifiConfiguration i : list ) {
      println(i.SSID);
      if (i.SSID != null && i.SSID.equals("\"" + "test" + "\"")) {
        //here i only adapt your code

        println("Disconnecting from all networks");
        wifiManager.disconnect();
        wifiManager.enableNetwork(i.networkId, true);
        wifiManager.reconnect();  
        println("connecting to "+i.SSID);

        break;
      }
    }
  }
}

class WiFiListItem {
  String name;
  int level;

  WiFiListItem(String name, int level) {
    this.name = name;
    this.level = level;
  }
}

Update2:通过更改void connect上的wifi管理员注册来修复错误(愚蠢的错误)。

然而,主要问题仍然存在:D如果未知的

,它不会连接到受损网络

1 个答案:

答案 0 :(得分:0)

通过查阅您正在使用的课程的参考资料,可以最好地回答这些问题。 HereScanResult的引用,这是i变量的内容。

该引用不包含networkId变量,这是您的错误告诉您的。请查阅参考资料,找到您正在寻找的变量或方法。