I am using following code to connect with WPA2 in android (I can connect with WEP and WPA). But I am getting only 'Scanning' status. And I am unable to connect with WPA2 network. Can you tell me what changes I need to make this code relevant with wpa2 WiFi.
private boolean saveWepConfigAndEnableNetwork(String ssid, String pass) {
isAlreadyPresend = false;
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + ssid + "\""; // IMP! This should be in Quotes!!
wc = checkPreviousConfiguration(wc);
wc.hiddenSSID = true;
wc.status = WifiConfiguration.Status.DISABLED;
wc.priority = 40;
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wc.preSharedKey = "\"" + pass + "\"";
wc.wepKeys[0] = "\"" + pass + "\""; // This is the WEP Password
wc.wepTxKeyIndex = 0;
boolean res1 = wifi.setWifiEnabled(true);
int res = 0;
if(isAlreadyPresend){
res = wifi.addNetwork(wc);
}else{
res = wifi.updateNetwork(wc);
}
Log.d("WifiPreference", "add Network returned " + res);
boolean es = wifi.saveConfiguration();
Log.d("WifiPreference", "saveConfiguration returned " + es);
boolean b = wifi.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
return b;
}
// Check if this SSID is already stored. If it is, return that
// configuration.
// If not, return the configuration being tested.
public WifiConfiguration checkPreviousConfiguration(WifiConfiguration wc) {
List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
if (config.SSID.equals(wc.SSID)){
isAlreadyPresend = true;
return config;
}
}
return wc;
}
Here is the code which worked for me to connect with WPA2
// Adding a WPA or WPA2 network
public static void changeNetworkWPA(WifiManager wifiManager, String ssid, String password) {
WifiConfiguration config = changeNetworkCommon(ssid);
// Hex passwords that are 64 bits long are not to be quoted.
config.preSharedKey = quoteNonHex(password, 64);
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
updateNetwork(wifiManager, config);
}
Code: From Zxing library
Related
First of all, I'd just like to point out that I'm a junior dev breaking new ground here for myself. I'm trying to send an ADB command to my Oculus to change the texture quality so that I don't have to hook up my Oculus to my PC every time with SideQuest. I've had no luck and there's no documentation that I can find to do this. Here's the code I have...
Retrieving the correct endpoint
private static UsbEndpoint getCorrectEndpoint(UsbDevice device, boolean outEndpoint) {
UsbEndpoint result = null;
//get interfaces
ArrayList<UsbInterface> usbInterfaceArrayList = new ArrayList<>();
for (int i = 0; i < device.getInterfaceCount(); i++) {
usbInterfaceArrayList.add(device.getInterface(i));
}
//get endpoints from those interfaces
UsbEndpoint endpointOut = null;
UsbEndpoint endpointIn = null;
for (int i = 0; i < usbInterfaceArrayList.get(0).getEndpointCount(); i++) {
if (usbInterfaceArrayList.get(0).getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbInterfaceArrayList.get(0).getEndpoint(i).getDirection() == UsbConstants.USB_DIR_OUT) {
endpointOut = usbInterfaceArrayList.get(0).getEndpoint(i); //If this Endpoint is XFER_BULK and DIR_OUT
} else {
endpointIn = usbInterfaceArrayList.get(0).getEndpoint(i); //If this EndPoint is XFER_BULK and DIR_IN
}
}
}
if (outEndpoint) { //Check the parameter to see which endpoint the user wants
result = endpointOut;
} else {
result = endpointIn;
}
return result;
}
Sending the data
public static void setOculusTexture(double textureWidth, Context context, Intent intent, TextView textView) {
double textureHeight = textureWidth * 1.0997;
boolean forceClaim = true;
int timeout = 0;
String textureString = "adb shell " + OculusADBConstants.OCULUS_TEXTURE_ADB_BASE + "Width " + textureWidth +
" && " + OculusADBConstants.OCULUS_TEXTURE_ADB_BASE + "Height " + textureHeight;
byte[] textureStringBytes = textureString.getBytes();
if (getOculusDeviceFromUSB(context) != null) { //If there is an Oculus connected
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
UsbDevice usbDevice = (UsbDevice) getOculusDeviceFromUSB(context);
UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(usbDevice);
usbDeviceConnection.claimInterface(usbDevice.getInterface(0), forceClaim);
int cmdBulkTransfer = usbDeviceConnection.bulkTransfer(getCorrectEndpoint(usbDevice, true), textureStringBytes, textureStringBytes.length, timeout);
int controlTransferResult = usbDeviceConnection.controlTransfer(UsbConstants.USB_DIR_OUT, 1,
0, 0, textureStringBytes, textureStringBytes.length, timeout);
textView.append(textureString + " data sent to device..." + "\n");
textView.append("cmdBulkTransfer Result = " + (cmdBulkTransfer) + "\n");
textView.append("ControlTransfer Result = " + controlTransferResult);
} else { //If there isn't an Oculus connected
Toast.makeText(context, "No Oculus detected. Is it plugged into your phone?", Toast.LENGTH_LONG).show();
}
}
The bulk transfer returns an actual number while the controlled transfer returns -1. I'm fairly sure that I need to somehow initiate an ADB request from my phone, but I have no idea how to do that. I assume this because when I connect my phone to the Oculus, and use the BugJaeger app, the BugJaeger app somehow makes the Oculus prompt with allowing USB Debugging dialog. My app does not cause that to happen. What am I doing wrong?
I want to connect a specific Wi-Fi network in Android 9 (api 28) programmatically.
I tried below code to connect.
public boolean ConnectToNetworkWPA(String networkSSID, String password) {
try {
WifiManager wifiManager = (WifiManager)
this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
boolean b = wifiManager.isWifiEnabled();
if (!b) {
wifiManager.setWifiEnabled(true);
}
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain SSID in quotes
conf.preSharedKey = "\"" + password + "\"";
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
conf.priority = 40;
Log.d("connecting", conf.SSID + " " + conf.preSharedKey);
int netid=wifiManager.addNetwork(conf);
Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
Log.d("re connecting", i.SSID + " " + conf.preSharedKey);
break;
}
}
//WiFi Connection success, return true
return true;
} catch (Exception ex) {
System.out.println(Arrays.toString(ex.getStackTrace()));
return false;
}
}
I tried this code in android 7 it is working but not working in android 9. By the android docs, these methods still work with API level 28.
Thanks for any ideas and help
I have got a list of configured Wifi Networks by wifiManager.getConfiguredNetworks() method. I displayed them in a Listview. Now whichever listItem I click , it connects to the same single Network only. I want to connect to the network that was clicked.
Here is my Java code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String networkSSID = list.get(position).SSID;
String networkPass = list.get(position).preSharedKey;
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\""+ networkPass +"\"";
int netId = wifiManager.addNetwork(conf);
wifiManager.disconnect();
wifiManager.enableNetwork(netId,true);
wifiManager.reconnect();
}
});
I use below block of code
private void connectToAP(String ssid, String passkey) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
Log.i(TAG, "* connectToAP");
WifiConfiguration wifiConfiguration = new WifiConfiguration();
List<ScanResult> scanResultList = wifiManager.getScanResults();
for (ScanResult result : scanResultList) {
if (result.SSID.equals(ssid)) {
String securityMode = getScanResultSecurity(result);
if (securityMode.equalsIgnoreCase("OPEN")) {
wifiConfiguration.SSID = "\"" + ssid + "\"";
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int res = wifiManager.addNetwork(wifiConfiguration);
Log.d(TAG, "# add Network returned " + res);
boolean b = wifiManager.enableNetwork(res, true);
Log.d(TAG, "# enableNetwork returned " + b);
wifiManager.setWifiEnabled(true);
} else if (securityMode.equalsIgnoreCase("WEP")) {
wifiConfiguration.SSID = "\"" + ssid + "\"";
wifiConfiguration.wepKeys[0] = "\"" + passkey + "\"";
wifiConfiguration.wepTxKeyIndex = 0;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
int res = wifiManager.addNetwork(wifiConfiguration);
Log.d(TAG, "### 1 ### add Network returned " + res);
boolean b = wifiManager.enableNetwork(res, true);
Log.d(TAG, "# enableNetwork returned " + b);
wifiManager.setWifiEnabled(true);
}
wifiConfiguration.SSID = "\"" + ssid + "\"";
wifiConfiguration.preSharedKey = "\"" + passkey + "\"";
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 = wifiManager.addNetwork(wifiConfiguration);
Log.d(TAG, "### 2 ### add Network returned " + res);
wifiManager.enableNetwork(res, true);
boolean changeHappen = wifiManager.saveConfiguration();
if (res != -1 && changeHappen) {
Log.d(TAG, "### Change happen");
} else {
Log.d(TAG, "*** Change NOT happen");
}
wifiManager.setWifiEnabled(true);
}
}
}
I need to check all the available wifi and then connect to a different one which I am currently connected to.
Sample - device is connect to AP01
private void switchAP(String ssid, String pass)) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\"";
if(!TextUtils.isEmpty(pass))
conf.wepKeys[0] = "\"" + pass + "\"";
conf.preSharedKey = "\"" + pass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiManager wifiManager = (WifiManager) SyncActivity.this.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
// List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
List<ScanResult> list = wifiManager.getScanResults();
for (ScanResult i : list) {
Log.w(TAG, "WIFI LIST > " + i.SSID);
if (i.SSID != null && i.SSID.equals(ssid)) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true); //>i.networkId Does not work - only in List<WifiConfiguration>…
wifiManager.reconnect();
logMsg("WiFi connection switched to " + ssid);
break;
}
}
}
Then I call
switchAP("AP02", ""));
i can not connect because this i.networkId does not seem to work when I use ScanResult rather than WifiConfiguration.
Has anyone came across this ?
Thanks guys.
The reason why I am not using List is because the device has never been connect to this SSOD before.
and List only returns all the previews connected network.
You need to use WifiConfiguration.Status.ENABLED.
An example code is written below for you:
public void WIFI_CONNECT_WIFI (String ssid, String password)
{
WifiManager wifi_manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifi_configuration = new WifiConfiguration();
wifi_configuration.SSID = String.format("\"%s\"", ssid);
wifi_configuration.preSharedKey = String.format("\"%s\"", password);
if (WIFI_NETWORK_EXIST (wifi_configuration) == true) {
wifi_configuration.status = WifiConfiguration.Status.ENABLED;
wifi_configuration.priority = 40;
}
else {
boolean result = wifi_manager.getConfiguredNetworks().add(wifi_configuration);
if (result == false) {
return;
}
wifi_configuration.status = WifiConfiguration.Status.ENABLED;
wifi_configuration.priority = 40;
wifi_configuration.networkId = wifi_manager.addNetwork(wifi_configuration);
}
wifi_manager.enableNetwork(wifi_configuration.networkId, true);
wifi_manager.saveConfiguration();
}
-
public boolean WIFI_NETWORK_EXIST (WifiConfiguration wifi_configuration)
{
WifiManager wifi_manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
for (WifiConfiguration config : wifi_manager.getConfiguredNetworks()) {
if (wifi_configuration.SSID.equals(config.SSID)) {
wifi_configuration.networkId = config.networkId;
return true;
}
}
return false;
}
And by the way, if there's a possibility to get SSID null, you are always gonna crash on your if comparison when SSID comes with null a value since you are trying to use a member function of a null value.
if (i.SSID != null && i.SSID.equals(ssid)) {
// ...
}
expected stack trace is: "bla bla bla trying to use String.equals(String) on a null value."
You should do an inner or different if after null comparison for equals(...) comparison.
I would like to build an app, that checks all the available WiFi networks,
If a network's SSID matches a search key then connect to that network, if two networks match then connect to the one with the higher signal strength.
e.g. SearchKey = "Open";
here is the code to check check all the wifi names :
if (networkInfo.isConnected()) {
ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();
List<ScanResult> results = wifiManager.getScanResults();
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " " + result.capabilities;
Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);
}
Then I would need to
Arrays.asList(mItems).contains("Open")
I am stuck here, How to do a proper check if the keyword "Open" exits, if so, then get the whole name and use below. ?
online sample how to conenct.
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);
WifiManager wifiManager = (WifiManager).getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
UPDATE CODE ------------------------------ - --------------------------------- - -- ---------------------------------------
How to check, This works But Now I need to implement Search by signal strength
if (!result.SSID.isEmpty()) {
String key = result.SSID + " " + result.capabilities;
Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);
if(result.SSID.contains("Open")) {
String useSSID = result.SSID;
Log.w(TAG, "useSSID => " + useSSID);
connectToWifi(MainActivity.this, useSSID);
break;
}
else { Log.e(TAG, "NO result contains"); }
Now how can I query my :
ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) > calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
}
}
if(mItems.contains("Open")) {
String useSSID = mItems #how to the name SSID name from mItems ???
Log.w(TAG, "useSSID => " + useSSID);
connectToWifi(MainActivity.this, useSSID);
break;
}
else { Log.e(TAG, "NO result contains"); }
=== Now my question is how to the SSID name from mItems ?
Thanks guys for your help.
Here is a snippet for the same:
public string getValidSSID()
{
List<ScanResult> results = wifiManager.getScanResults();
HashMap<String,ScanResult> distinctNetworks = new HashMap<String, ScanResult>();
for(ScanResult scanResult : results)
{
if(scanResult.SSID.contains("Open"))
{
if(!distinctNetworks.containsKey(scanResult))
{
distinctNetworks.put(scanResult.SSID, scanResult);
}
else
{
if(WifiManager.compareSignalLevel(scanResult.level, distinctNetworks.get(scanResult.SSID).level)>0)
{
distinctNetworks.put(scanResult.SSID, scanResult);
}
}
}
}
Set<String> networks = distinctNetworks.keySet();// This will only contain one key which will be ths ssid with the max strength containing "open" in SSID
for (String s : networks) {
return s;
}
}