Android connect to Wifi programmatically if wifi name match - java

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

Related

How to send ADB commands to USB Host-connected device (Oculus)

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?

Trying to pull list of users from large AD Group via Java - only get 1500 back - how can i get all the user list?

Trying to pull the list of users from large AD Groups via Java - but only get 1500 back - how can I get all the users?
// Step1 method - Pulling ADGroups from Active Directory
private static void getADGroups() {
Hashtable<String, Object> env = new Hashtable<String, Object>(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://");
env.put(Context.SECURITY_PRINCIPAL, "xxxx");
env.put(Context.SECURITY_CREDENTIALS, "1233");
env.put(Context.REFERRAL, "follow");
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
// Activate paged results
int pageSize = 10000;
byte[] cookie = null;
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
int total;
do {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { "cn" };
searchControls.setReturningAttributes(attrIDs);
String searchBase = "OU=Groups,DC=cof,DC=ds,DC=com";
String searchFilter = "CN=*Ranger*";
/* perform the search */
NamingEnumeration results = ctx.search(searchBase, searchFilter, searchControls);
/* for each entry print out name + all attrs and values */
int count = 0;
while (results != null && results.hasMore()) {
SearchResult entry = (SearchResult) results.next();
//System.out.println(count + ")" + entry.getName());
count = count + 1;
String gname = entry.getName();
//System.out.println("gname before split " + gname);
String[] gnames = gname.split(",");
gname = gnames[0];
//System.out.println("gname after split - 1 " + gname);
gname = gname.substring(3);
//System.out.println("gname after split - 2 " + gname);
groups.add(gname);
}
//System.out.println("count : " + count);
// Examine the paged results control response
Control[] controls = ctx.getResponseControls();
//System.out.println("controls-size : " + controls.length);
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
total = prrc.getResultSize();
//System.out.println("total : " + total);
if (total != 0) {
//System.out.println("*****************
cookie = prrc.getCookie();
//System.out.println("cookie : " + cookie);
}
}
} else {
System.out.println("No controls were sent from the server");
}
// Re-activate paged results
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
} while (cookie != null);
} catch (NamingException e) {
System.out.println("PagedSearch failed." + e.getMessage());
e.printStackTrace();
} catch (IOException ie) {
System.out.println("PagedSearch failed." + ie.getMessage());
ie.printStackTrace();
} finally {
try {
ctx.close();
} catch (NamingException e) {
System.out.println("PagedSearch failed (error occured in closing context)." + e.getMessage());
e.printStackTrace();
}
}
}
// Step2 method - to pull users from ADgroups that we got for above
private static void getGroupMembers(String groupName) {
searchBase = "Ou=users";
String returnedAtts[] = { "member" };
searchControls.setReturningAttributes(returnedAtts);
searchFilter = String.format("(cn=%s)", groupName);
// System.out.println(searchFilter);
getSearchResult();
filterSearchResultsForGroupMembers(groupName);
} // end of method.
`
The key is where you request the member attribute. If you get back exactly 1500 results, you know there might be more. This is how you request the next batch:
String[] returnedAtts = { "member;range=1500-*" };
Then if you get exactly 1500 back again, you need to ask for more (`member;range=3000-*1). Keep asking for more until you get less than 1500 back.
So setup a loop with a counter and use that counter in the range string.
There is a full example here (search the page for "setReturningAttributes" to find that section of the code): https://community.oracle.com/thread/1157644

Android switch AP programmatically

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.

Extracting Data from pdf417 such as Drivers License

I have an Android application in which i am scanning PDF417 barcode image. After scanning the Barcode i am getting the result as below.
#
ANSI 636014040002DL00410477ZC05180089DLDAQD1234562 XYXYXYXYXYXYXYXYX
DCSLASTNAMEXYXYXYXYXYXYXYXYXXYXYXYXYXYXYXYX
DDEU
DACFIRSTXYXYXYXYXYXYXYXYXXYXYXYXYXYXYXYXXYX
DDFU
DADXYXYXYXYXYXYXYXYXXYXYXYXYXYXYXYXXYXYXYXY
DDGU
DCAA XYXY
DCBNONEY1XY1XY1
DCDNONEX
DBD10312009
DBB10311977
DBA10312014
DBC1
DAU068 IN
DAYBRO
DAG1234 ANY STREET XY1XY1XY1XY1XY1XY1X
DAICITY XY1XY1XY1XY1XY1
DAJCA
DAK000000000
DCF00/00/0000NNNAN/ANFD/YY X
DCGUSA
DCUSUFIX
DAW150
DAZBLK XY1XY1XY
DCKXY1XY1XY1XY1XY1XY1XY1XY1X
DDAF
DDBMMDDCCYY
DDD1
ZCZCAY
ZCBCORR LENS
ZCCBRN
ZCDXYX
ZCEXYXYXYXYXYXYXY
ZCFXY1XY1XY1XY1XY1XY1XYXYXYXYXYXYXY
I want to get details like FirstName, LastName, City, Address etc from the above String.
Can anyone please tell me how do i get the details.
Thanks.
Please see below link and generate the parser to extract the information of driver License.
http://www.dol.wa.gov/external/docs/barcodeCalibration-EDLEID.pdf
I have make this decoder for ios app
here the code :
NSString *message=barcode.barcodeString;
NSMutableArray *arrFixedData=[[NSMutableArray alloc]initWithObjects:#"DCS",#"DCT",#"DCU",#"DAG",#"DAI",#"DAJ",#"DAK",#"DCG",#"DAQ",#"DCA",#"DCB",#"DCD",#"DCF",#"DCH",#"DBA",#"DBB",#"DBC",#"DBD",#"DAU",#"DCE",#"DAY",#"ZWA",#"ZWB",#"ZWC",#"ZWD",#"ZWE",#"ZWF", nil];
NSMutableArray *arrDriverData=[[NSMutableArray alloc]initWithObjects:#"Customer Family Name",#"Customer Given Name",#"Name Suffix",#"Street Address 1",#"City",#"Jurisdction Code",#"Postal Code",#"Country Identification",#"Customer Id Number",#"Class",#"Restrictions",#"Endorsements",#"Document Discriminator",#"Vehicle Code",#"Expiration Date",#"Date Of Birth",#"Sex",#"Issue Date",#"Height",#"Weight",#"Eye Color",#"Control Number",#"Endorsements",#"Transaction Types",#"Under 18 Until",#"Under 21 Until",#"Revision Date", nil];
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
for (int i=0; i<[arrFixedData count]; i++)
{
NSRange range = [message rangeOfString: [arrFixedData objectAtIndex:i] options: NSCaseInsensitiveSearch];
NSLog(#"found: %#", (range.location != NSNotFound) ? #"Yes" : #"No");
if (range.location != NSNotFound)
{
NSString *temp=[message substringFromIndex:range.location+range.length];
NSRange end = [temp rangeOfString:#"\n"];
if (end.location != NSNotFound)
{
temp = [temp substringToIndex:end.location];
temp =[temp stringByReplacingOccurrencesOfString:#"\n" withString:#""];
temp=[temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
NSLog(#"temp data : %#",temp);
[dict setObject:temp forKey:[arrDriverData objectAtIndex:i]];
}
}
NSLog(#"Dictionary : %#",dict);
The barcodestring contains the data which are scanned from pdf 417.
Thanks
Here's the Decoder for Android
Here, The Parameter "data" contains the string which you have to scanned pdf417.
==========Properties=============
HashMap<String, String> myData = new HashMap<String, String>();
public final String Customer_Family_Name = "DCS", Customer_Given_Name = "DCT", Name_Suffix = "DCU",
Street_Address_1 = "DAG", City = "DAI", Jurisdction_Code = "DAJ", Postal_Code = "DAK",
Country_Identification = "DCG", Customer_Id_Number = "DAQ", Class = "DCA", Restrictions = "DCB",
Endorsements = "DCD", Document_Discriminator = "DCF", Vehicle_Code = "DCH", Expiration_Date = "DBA",
Date_Of_Birth = "DBB", Sex = "DBC", Issue_Date = "DBD", Height = "DAU", Weight = "DCE", Eye_Color = "DAY",
Control_Number = "ZWA", WA_SPECIFIC_ENDORSMENT = "ZWB", Transaction_Types = "ZWC", Under_18_Until = "ZWD",
Under_21_Until = "ZWE", Revision_Date = "ZWF", Customer_Full_Name = "DAA", Customer_First_Name = "DAC",
Customer_Middle_Name = "DAD", Street_Address_2 = "DAH", Street_Address_1_optional = "DAL",
Street_Address_2_optional = "DAM";
ArrayList<String> allKeys = new ArrayList<String>();
============Methods after Scaning================
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SCAN_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
ArrayList<BarcodeResult> barcodes = data.getParcelableArrayListExtra(BarcodeScanActivity.RESULT_EXTRA);
Log.e("BARCODE RESULT ", "<<<>>" + barcodes.toString());
String barcodeResult = barcodes.get(0).barcodeString;
String lines[] = barcodeResult.split("\\r?\\n");
for (int i = 0; i < lines.length; i++)
{
String str = lines[i];
if (str.contains("ANSI"))
{
str = str.substring(str.indexOf("DL"));
String str1[] = str.split("DL");
if (str1.length > 1)
{
str = str1[str1.length - 1];
}
}
if (str.length() > 3)
{
String key = str.substring(0, 3);
String value = str.substring(3);
if (allKeys.contains(key))
{
if (!value.equalsIgnoreCase("None"))
{
myData.put(allKeys.get(allKeys.indexOf(key)), value);
}
}
}
Log.e("RESULT ", "<<>>" + lines[i]);
}
Log.e("TAG", "SO MAY BE FINAL RESULT");
if (myData.containsKey(Customer_Family_Name))
{
Log.v("TAG", "users family name:" + myData.get(Customer_Family_Name));
lname = myData.get(Customer_Family_Name).trim();
}
if (myData.containsKey(Customer_Given_Name))
{
Log.v("TAG", "users Given name:" + myData.get(Customer_Given_Name));
try
{
String CustomerName[] = myData.get(Customer_Given_Name).split(" ");
fname = CustomerName[0].trim();
mname = CustomerName[1].substring(0, 1).trim();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (myData.containsKey(Name_Suffix))
{
Log.v("TAG", "Surname name:" + myData.get(Name_Suffix));
}
if (myData.containsKey(Street_Address_1))
{
Log.v("TAG", "Address line 1 :" + myData.get(Street_Address_1));
try
{
address = myData.get(Street_Address_1).trim();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (TextUtils.isEmpty(address))
{
if (myData.containsKey(Street_Address_2))
{
address = myData.get(Street_Address_2).trim();
}
if (TextUtils.isEmpty(address))
{
if (myData.containsKey(Street_Address_1_optional))
{
address = myData.get(Street_Address_1_optional).trim();
}
}
if (TextUtils.isEmpty(address))
{
if (myData.containsKey(Street_Address_2_optional))
{
address = myData.get(Street_Address_2_optional).trim();
}
}
}
if (myData.containsKey(City))
{
Log.v("TAG", "City:" + myData.get(City));
city = myData.get(City).trim();
}
if (myData.containsKey(Jurisdction_Code))
{
Log.v("TAG", "State:" + myData.get(Jurisdction_Code));
State = myData.get(Jurisdction_Code).trim();
}
if (myData.containsKey(Postal_Code))
{
Log.v("TAG", "Pin Code:" + myData.get(Postal_Code));
zipcode = myData.get(Postal_Code).substring(0, 5).trim();
}
if (myData.containsKey(Date_Of_Birth))
{
Log.v("TAG", "Birth Date :" + myData.get(Date_Of_Birth));
birthday = myData.get(Date_Of_Birth).substring(0, 2) + "/" + myData.get(Date_Of_Birth).substring(2, 4)
+ "/" + myData.get(Date_Of_Birth).substring(4);
if (isThisDateValid(birthday, "MM/dd/yyyy", myData.get(Date_Of_Birth)))
Log.e("TAG", "IS VALID");
else
Log.e("TAG", "IS NOT VALID");
}
if (myData.containsKey(Sex))
{
Log.v("TAG", "Sex:" + (myData.get(Sex).toString().trim().equals("1") ? "Male" : "Female"));
}
if (myData.containsKey(Customer_Full_Name))
{
String cName = myData.get(Customer_Full_Name);
int startIndexOfComma = 0;
int endIndexOfComma = 0;
startIndexOfComma = cName.indexOf(",");
endIndexOfComma = cName.lastIndexOf(",");
if (startIndexOfComma != endIndexOfComma)
{
String CustomerName[] = myData.get(Customer_Full_Name).split(",");
lname = CustomerName[0].replace(",", "").trim();
fname = CustomerName[1].trim();
mname = CustomerName[2].substring(0, 1).trim();
}
else
{
String CustomerName[] = myData.get(Customer_Full_Name).split(" ");
lname = CustomerName[0].replace(",", "").trim();
fname = CustomerName[1].trim();
mname = CustomerName[2].substring(0, 1).trim();
}
}
if (myData.containsKey(Customer_First_Name))
{
fname = myData.get(Customer_First_Name).trim();
}
if (myData.containsKey(Customer_Middle_Name))
{
mname = myData.get(Customer_Middle_Name).substring(0, 1).trim();
}
// TODO edit here at 7/3/2014
if (myData.containsKey(Customer_Id_Number))
{
licence_number = myData.get(Customer_Id_Number).trim();
Log.e("TAG", "Licence Number is :" + licence_number);
}
if (myData.containsKey(Expiration_Date))
{
licence_expire_date = myData.get(Expiration_Date).trim();
licence_expire_date = myData.get(Expiration_Date).substring(0, 2) + "/"
+ myData.get(Expiration_Date).substring(2, 4) + "/" + myData.get(Expiration_Date).substring(4);
licence_expire_date = makeDateValid(licence_expire_date, "MM/dd/yyyy", myData.get(Expiration_Date));
Log.e("TAG", "expire date is :" + licence_expire_date);
}
etFirstName.setText(fname.trim());
etMiddleName.setText(mname.trim());
etLastName.setText(lname.trim());
etAddress.setText(address.trim());
etZipCode.setText(zipcode.trim());
etCity.setText(city.trim());
etState.setText(State.trim());
etDLNumber.setText(licence_number);
etDLExpirationDate.setText(licence_expire_date);
etBirthDay.setText(birthday.trim());
}
}
Here's the code I use to decode the PDF417 data in Swift.
private let pdf417Map: [String: String] = [
"DAA":"Full Name",
"DAB":"Family Name",
"DAC":"Given Name",
"DAD":"Middle Name",
"DAE":"Name Suffix",
"DAF":"Name Prefix",
"DAG":"Mailing Street Address1",
"DAH":"Mailing Street Address2",
"DAI":"Mailing City",
"DAJ":"Mailing Jurisdiction Code",
"DAK":"Mailing Postal Code",
"DAL":"Residence Street Address1",
"DAM":"Residence Street Address2",
"DAN":"Residence City",
"DAO":"Residence Jurisdiction Code",
"DAP":"Residence Postal Code",
"DAQ":"License or ID Number",
"DAR":"License Classification Code",
"DAS":"License Restriction Code",
"DAT":"License Endorsements Code",
"DAU":"Height in FT_IN",
"DAV":"Height in CM",
"DAW":"Weight in LBS",
"DAX":"Weight in KG",
"DAY":"Eye Color",
"DAZ":"Hair Color",
"DBA":"License Expiration Date",
"DBB":"Date of Birth",
"DBC":"Sex",
"DBD":"License or ID Document Issue Date",
"DBE":"Issue Timestamp",
"DBF":"Number of Duplicates",
"DBG":"Medical Indicator Codes",
"DBH":"Organ Donor",
"DBI":"Non-Resident Indicator",
"DBJ":"Unique Customer Identifier",
"DBK":"Social Security Number",
"DBL":"Date Of Birth",
"DBM":"Social Security Number",
"DBN":"Full Name",
"DBO":"Family Name",
"DBP":"Given Name",
"DBQ":"Middle Name or Initial",
"DBR":"Suffix",
"DBS":"Prefix",
"DCA":"Virginia Specific Class",
"DCB":"Virginia Specific Restrictions",
"DCD":"Virginia Specific Endorsements",
"DCE":"Physical Description Weight Range",
"DCF":"Document Discriminator",
"DCG":"Country territory of issuance",
"DCH":"Federal Commercial Vehicle Codes",
"DCI":"Place of birth",
"DCJ":"Audit information",
"DCK":"Inventory Control Number",
"DCL":"Race Ethnicity",
"DCM":"Standard vehicle classification",
"DCN":"Standard endorsement code",
"DCO":"Standard restriction code",
"DCP":"Jurisdiction specific vehicle classification description",
"DCQ":"Jurisdiction-specific",
"DCR":"Jurisdiction specific restriction code description",
"DCS":"Last Name",
"DCT":"First Name",
"DCU":"Suffix",
"DDA":"Compliance Type",
"DDB":"Card Revision Date",
"DDC":"HazMat Endorsement Expiry Date",
"DDD":"Limited Duration Document Indicator",
"DDE":"Family Name Truncation",
"DDF":"First Names Truncation",
"DDG":"Middle Names Truncation",
"DDH":"Under 18 Until",
"DDI":"Under 19 Until",
"DDJ":"Under 21 Until",
"DDK":"Organ Donor Indicator",
"DDL":"Veteran Indicator",
"PAA":"Permit Classification Code",
"PAB":"Permit Expiration Date",
"PAC":"Permit Identifier",
"PAD":"Permit IssueDate",
"PAE":"Permit Restriction Code",
"PAF":"Permit Endorsement Code",
"ZVA":"Court Restriction Code"
]
// metadataObj = # ANSI 63601404....
if metadataObj.stringValue != nil {
let licenseData = metadataObj.stringValue!.components(separatedBy: "\n")
var customerProfile: [[String: String]] = []
for item in licenseData {
var metaDataItem = item
if metaDataItem.count > 3 {
if let dlCodeRange = metaDataItem.range(of: "DAQ") {
let dlStart = dlCodeRange.lowerBound
let dlEnd = metaDataItem.index(metaDataItem.endIndex, offsetBy: 0)
let dlNoRange = dlStart..<dlEnd
metaDataItem = String(metaDataItem[dlNoRange])
}
// Get the 3 letter code
let pdf417Code = String(metaDataItem.prefix(3))
// See if the code exists in the map
if pdf417Map[pdf417Code] != nil {
// Code exists in map, save to profile
let start = metaDataItem.index(metaDataItem.startIndex, offsetBy: 3)
let end = metaDataItem.index(metaDataItem.endIndex, offsetBy: 0)
let range = start..<end
let extractedData = metaDataItem[range]
customerProfile.append([pdf417Map[pdf417Code]!: String(extractedData)])
}
}
}
print("customerProfile: \(customerProfile)")
}
Please look into this Link having decoder for driver license in Java. It might help.

Unable to connect with WPA2 android

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

Categories