我已经在网上试了几个教程试图在android studio上创建一个wifi扫描程序,但我遇到了WifiManager的getConfiguredNetworks()方法的问题。它不断返回null而不是预期的List。
我已经在网上进行了一些搜索,似乎我的代码一直在抛出一个RemoteException。即使阅读了http://docs.oracle.com/javase/7/docs/api/java/rmi/RemoteException.html上的文档,我仍然不明白RemoteExcecption是什么或如何解决它。
以下是我的代码片段:
wifi=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
Log.d("WifiInfo", "info is: " + info);
// list available network
List<WifiConfiguration> configurations = wifi.getConfiguredNetworks(); //configurations is null
Log.d("List<WifiConfig>", "configurations is: " + configurations); //error thrown here
// Is WiFi on?
if (wifi.isWifiEnabled()) {
// Check for existing APs.
for(WifiConfiguration config : configurations) {
Log.d("CONFIG", config.toString());
myItems.add(config.toString());
}
}
有人可以帮助我吗?
答案 0 :(得分:0)
使用此代码..
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textStatus = (TextView) findViewById(R.id.test1);
buttonScan = (Button) findViewById(R.id.btn);
buttonScan.setOnClickListener(MainActivity.this);
lv = (ListView) findViewById(R.id.listview_item);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(MainActivity.this, arraylist, R.layout.raw, new String[]{ITEM_KEY}, new int[]{R.id.row});
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent intent) {
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, arraylist.get(position).toString(), Toast.LENGTH_SHORT).show();
connectToAP(arraylist.get(position).get("key"), "");
}
});
}
public void connectToAP(String ssid, final String passkey) {
final WifiConfiguration wifiConfiguration = new WifiConfiguration();
final String networkSSID = ssid;
final String[] networkPass = {passkey};
final String[] password = {""};
for (ScanResult result : results) {
if (result.SSID.equals(networkSSID)) {
String securityMode = getScanResultSecurity(result);
if (securityMode.equals("PSK")) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Password");
dialog.setMessage("Enter Passsword");
final EditText editText = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
editText.setLayoutParams(lp);
dialog.setView(editText);
dialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
password[0] = editText.getText().toString();
wifiConfiguration.SSID = "\"" + networkSSID + "\"";
wifiConfiguration.preSharedKey = "\"" + editText.getText().toString() + "\"";
wifiConfiguration.hiddenSSID = true;
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
int res = wifi.addNetwork(wifiConfiguration);
wifi.enableNetwork(res, true);
boolean changeHappen = wifi.saveConfiguration();
if (res != -1 && changeHappen) {
// .connectedSsidName = networkSSID;
} else {
// Log.d(TAG, "*** Change NOT happen");
}
wifi.setWifiEnabled(true);
}
});
dialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
if (securityMode.equalsIgnoreCase("OPEN")) {
wifiConfiguration.SSID = "\"" + networkSSID + "\"";
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int res = wifi.addNetwork(wifiConfiguration);
boolean b = wifi.enableNetwork(res, true);
wifi.setWifiEnabled(true);
} else if (securityMode.equalsIgnoreCase("WEP")) {
wifiConfiguration.SSID = "\"" + networkSSID + "\"";
wifiConfiguration.wepKeys[0] = "\"" + password[0] + "\"";
wifiConfiguration.wepTxKeyIndex = 0;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
int res = wifi.addNetwork(wifiConfiguration);
boolean b = wifi.enableNetwork(res, true);
wifi.setWifiEnabled(true);
}
}
}
}
public String getScanResultSecurity(ScanResult scanResult) {
final String cap = scanResult.capabilities;
final String[] securityModes = {"WEP", "PSK", "EAP"};
for (int i = securityModes.length - 1; i >= 0; i--) {
if (cap.contains(securityModes[i])) {
return securityModes[i];
}
}
return "OPEN";
}
public void onClick(View view) {
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try {
size = size - 1;
while (size >= 0) {
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID);
item.put("capablity", results.get(size).capabilities);
adapter.notifyDataSetChanged();
arraylist.add(item);
size--;
}
} catch (Exception e) {
}
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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"
tools:context="com.example.admin.wifi.MainActivity">
<ListView
android:id="@+id/listview_item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<Button
android:id="@+id/btn"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="scan" />
</RelativeLayout>
raw.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:id="@+id/row"
android:layout_height="wrap_content" />
</LinearLayout>
maifest
答案 1 :(得分:0)
我刚才也处于这种情况。第一项:getConfiguredNetworks()
在wifi关闭时始终返回null。同样,WifiService似乎在setWifiEnabled(true)
和getConfiguredNetworks()
之间需要一点时间。.我创建了一个小循环,只设法打印了一个日志:
wifiMgr.setWifiEnabled(true); // else we won't be able to read the networks
while (wifiMgr.getWifiState() != WIFI_STATE_ENABLED) {
LogIf.d("FOO", "waiting for wifi-system to provide network-data");
}
for (WifiConfiguration cfg : wifiMgr.getConfiguredNetworks()) {
..
使用处理程序在WifiService上签入直到打开完成可能会更好。