我需要创建一个应用程序来扫描并收集可用的接入点列表,包括信号强度。出于某种原因,每次我启动WifiManager.startScan()方法时,它都返回true,但我的广播接收器永远不会被调用。
以下是我班级的代码:
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.Handler;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Manages radio (wifi) information
*/
public class NetworkManager {
private final Handler handler = new Handler();
private WifiReceiver receiverWifi;
private TextView mTextView;
// true if scan is done
private boolean mDone = true;
private WifiManager mManager;
List<ScanResult> results;
// Data in form SSID, RSSI
ArrayList<HashMap<String, String>> oldData = new ArrayList<>();
ArrayList<HashMap<String, String>> data = new ArrayList<>();
public NetworkManager(Context c, TextView mTextView) {
this.mTextView = mTextView;
mManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
if (!mManager.isWifiEnabled())
mManager.setWifiEnabled(true);
receiverWifi = new WifiReceiver();
c.registerReceiver(receiverWifi,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
if (mManager.isWifiEnabled() == false)
mManager.setWifiEnabled(true);
scanAndSet();
Log.d("TAG", "Constructor after scan and set");
WifiInfo wifiInfo = mManager.getConnectionInfo();
Log.d("TAG", wifiInfo.toString());
}
/**
* Sets the SSID and RSSI from the scanned results into main data bin.
*/
// private void setNetworkData() {
// String result = "";
// oldData = data;
// data.clear();
// for(ScanResult r : results) {
// String ssid = r.SSID;
// String rssi = String.valueOf(r.level);
// HashMap<String, String> x = new HashMap<>();
// x.put(ssid, rssi);
// result += "ID: " + ssid + " - RSSI" + rssi + "/n";
// Log.d("TAG", "R: " + result);
// }
// mDone = true;
// }
public void scanAndSet() {
handler.post(new Runnable() {
@Override
public void run() {
Log.d("TAG", "Start: " + mManager.startScan());
}
});
}
public boolean isDone() {
return mDone;
}
class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "On receive broadcast receiver");
ArrayList<String> connections=new ArrayList<String>();
ArrayList<Float> Signal_Strenth= new ArrayList<Float>();
List<ScanResult> wifiList = mManager.getScanResults();
for(int i = 0; i < wifiList.size(); i++) {
connections.add(wifiList.get(i).SSID);
}
}
}
}
scanAndSet()方法用于启动扫描。 startScan()方法返回true。只有当我进入设置并且设备搜索wifi网络时才会调用接收器,我似乎无法以编程方式执行此操作。
另一个特殊的事情是当我想使用WifiManager.getConnectionInfo().toString()
获取连接的接入点的信息时,这就是它所给出的。
D/TAG: SSID: <unknown ssid>, BSSID: <none>, Supplicant state: COMPLETED, RSSI: -127, Link speed: -1Mbps, Frequency: -1MHz, Net ID: -1, Metered hint: false, score: 0
我完全迷失了,这在所有Wear设备中都很常见,还是禁用了无线网络API?