Related
Is it possible to save a logcat entry in a sqlite database?
If a user got an error I want to read the logs without having the phone connected to adb.
This is how I write logs: Log.d(TAG, "An error occured", e)
Thanks
Creating a log file will be better option to read error
public void mlogFile(String pActivityName, String pOperation, String pData) {
File lLogFilePath, lLogFile;
Date lDate;
CharSequence lCurrfolder;
FileWriter lFileWriter;
BufferedWriter lBuffWriter;
String lActivity, lOperation;
try {
lDate = new Date();
lCurrfolder = DateFormat.format("yyyyMMdd", lDate.getTime());
lLogFilePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "CSPDCLData/" + lCurrfolder + "/");
if (!lLogFilePath.exists()) {
lLogFilePath.mkdirs();
}
lLogFile = new File(lLogFilePath, "ADDLogfile.txt");
lFileWriter = new FileWriter(lLogFile, true);
lBuffWriter = new BufferedWriter(lFileWriter);
lActivity = pActivityName.length() != 0 ? ADDPadding(pActivityName, 25, ' ', 'L') + "~ " : "";
lOperation = pOperation.length() != 0 ? " : " + pData : "";
lBuffWriter.append(DateFormat.format("kk:mm:ss", lDate.getTime()) + " " + lActivity + pOperation + lOperation + "\n");
lBuffWriter.flush();
lBuffWriter.close();
lFileWriter.close();
} catch (IOException ex) {
Toast.makeText(this, "ERROR: " + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
And at the time of error add this line
logFile(getClass().getSimpleName(),"methodName()", "An error occured"+ e.getMessage());
I have an app that reads notifications to the driver while driving. I am trying to parse the various notifications. Those that use the old 'tickerText' work fine but several apps like Skype don't support that. Instead, the text in the notification after the first message just says something like "3 new messages". Not very helpful. I want the last message string instead. I wrote this:
public class Catcher extends NotificationListenerService {
File file;
String dir;
File save;
int count = 0;
#Override
public void onCreate() {
super.onCreate();
dir = Environment.getExternalStorageDirectory() + "/NotCatch";
save = new File(dir);
if(!save.exists()){
save.mkdirs();
}
//Toast.makeText(this, dir + " " + file.getName(), Toast.LENGTH_LONG).show();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
file = new File(save, "NotCatch" + count + ".txt");
count++;
String temp = "";
String[] lines;
Notification not = sbn.getNotification();
temp += "Category: " + not.category+ "\n";
temp+= "TickerText: " + not.tickerText + "\n";
temp += "Extras..."+ "\n";
Bundle bun = not.extras;
temp+= "BigText: " + bun.getString(Notification.EXTRA_BIG_TEXT)+ "\n";
temp+= "SummaryText: " + bun.getString(Notification.EXTRA_SUMMARY_TEXT)+ "\n";
temp+= "InfoText: " + bun.getString(Notification.EXTRA_INFO_TEXT)+ "\n";
temp+= "Text: " + bun.getString(Notification.EXTRA_TEXT)+ "\n";
temp+= "TextLines: " + bun.getString(Notification.EXTRA_TEXT_LINES)+ "\n";
temp+= "SubText: " + bun.getString(Notification.EXTRA_SUB_TEXT) + "\n";
temp+= "Title:" + bun.getString(Notification.EXTRA_TITLE) +"\n";
temp+= "Big Title:" + bun.getString(Notification.EXTRA_TITLE_BIG) +"\n";
/* lines = bun.getString(Notification.EXTRA_TEXT_LINES).split("\n");
temp += "Lines... \n" ;
int cnt = 0;
for (String line : lines) {
temp+= cnt + ": " + line + "\n";
cnt++;
}*/
Looper.prepare();
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(temp.getBytes());
fos.close();
Toast.makeText(this,"File written", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
This is just what I have so far for testing of course. I can get the bundle from the notification but it can't get the string array of the message lines. It looks like this in the debugger. 'bun' below is the 'Bundle' from the 'Notification'.
My question is this. How do I get the array of strings that start with "some message text - 4"? This is the bundle from an Android Notification.
I finally was able to get the strings this way
CharSequence[] lines = bun.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
for(CharSequence line : lines){
temp+= "line: " + line.toString() + "\n";
}
Since the strings you are trying to retrieve are contained in the ArrayMap mMap (according to the debugger image), and as implementations of Map are serializable, you'll want to do the following to first retrieve that map:
ArrayMap map = bun.getSerializableExtra("mMap");
Then, you should be able to get the array of strings you want (which according to the debugger image is an array of CharSequence objects) with the following:
CharSequence[] messages = (CharSequence[]) map.valueAt(1);
An interesting read on bundles and maps:
https://medium.com/the-wtf-files/the-mysterious-case-of-the-bundle-and-the-map-7b15279a794e#.kf3m2haa3
I m trying to get email address from linkedin user after authenticate now i m getting basic profile but not getting email address.
I m using http://code.google.com/p/linkedin-j/downloads/list jar file for authentication.
i have read this document care fully but not use full for me http://oodlestechnologies.com/blogs/recent-changes-in-linkedin-api.
Below code for jar file properties :-
# API URLs
##########
# Profile API
com.google.code.linkedinapi.client.getProfileForCurrentUser=http://api.linkedin.com/v1/people/~{profileFields}
com.google.code.linkedinapi.client.getProfileById=http://api.linkedin.com/v1/people/id={id}{profileType}{profileFields}
com.google.code.linkedinapi.client.getProfileByUrl=http://api.linkedin.com/v1/people/url={url}{profileType}{profileFields}
#OAuth URLs
###########
com.google.code.linkedinapi.client.oauth.requestToken=https://api.linkedin.com/uas/oauth/requestToken
com.google.code.linkedinapi.client.oauth.accessToken=https://api.linkedin.com/uas/oauth/accessToken
com.google.code.linkedinapi.client.oauth.authorize=https://www.linkedin.com/uas/oauth/authorize
com.google.code.linkedinapi.client.oauth.invalidateToken=https://api.linkedin.com/uas/oauth/invalidateToken
when i m change on anything on above and creating jar its show error.
now i m shown my code :-
void startAutheniticate() {
System.out.println("OAUTH_CALLBACK_URL " + OAUTH_CALLBACK_URL);
final LinkedInRequestToken liToken = oAuthService
.getOAuthRequestToken(OAUTH_CALLBACK_URL);
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret())
.commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(uri
.getQueryParameter(OAUTH_QUERY_TOKEN),
pref.getString(PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(PREF_TOKEN, accessToken.getToken())
.putString(PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(PREF_REQTOKENSECRET).commit();
showCurrentUser(accessToken);
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.remove(PREF_TOKEN).remove(PREF_TOKENSECRET)
.remove(PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
final LinkedInApiClient client = factory
.createLinkedInApiClient(accessToken);
try {
final Person profile = client.getProfileForCurrentUser(EnumSet.of(
ProfileField.ID, ProfileField.FIRST_NAME,
ProfileField.LAST_NAME, ProfileField.HEADLINE,
ProfileField.INDUSTRY, ProfileField.PICTURE_URL,
ProfileField.DATE_OF_BIRTH, ProfileField.LOCATION_NAME,
ProfileField.MAIN_ADDRESS, ProfileField.LOCATION_COUNTRY
));
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call (this sample only check for current user
// and shows it in TextView)
// /////////////////////////////////////////////////////////
System.out.println("p => " + profile);
System.out.println("PersonID : " + profile.getId());
System.out.println("Name : " + profile.getFirstName() + " "
+ profile.getLastName());
System.out.println("Headline : " + profile.getHeadline());
System.out.println("Industry : " + profile.getIndustry());
System.out.println("Picture : " + profile.getPictureUrl());
DateOfBirth dateOfBirth = profile.getDateOfBirth();
System.out.println("DateOfBirth : " + dateOfBirth.getDay() + "/"
+ dateOfBirth.getMonth() + "/" + dateOfBirth.getYear());
System.out.println("MAin Address : " + profile.getMainAddress());
Location location = profile.getLocation();
System.out.println("Location:" + location.getName() + " - "
+ location.getCountry().getCode());
// get_from_last
Toast.makeText(LITestActivity.this, "Wait...", Toast.LENGTH_LONG).show();
startActivity(new Intent(LITestActivity.this,
UserProfileScreen.class)
.putExtra("get_from_last", "1")
.putExtra("getId", profile.getId())
.putExtra("getEmail", "email#add.com")
.putExtra("getFirstName", profile.getFirstName())
.putExtra("getLastName", profile.getLastName())
.putExtra("getHeadline", profile.getHeadline())
.putExtra("getPictureUrl", profile.getPictureUrl())
.putExtra(
"dob",
dateOfBirth.getDay() + "/" + dateOfBirth.getMonth()
+ "/" + dateOfBirth.getYear()));
finish();
} catch (LinkedInApiClientException ex) {
clearTokens();
Toast.makeText(
this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
pd.dismiss();
finish();
}
}
int i = 0;
public void onNewIntent(Uri intent) {
if (i == 0) {
i++;
finishAuthenticate(intent);
} else {
i++;
}
System.out.println("i => " + i);
}
but i m stuck how to get email address so can any one help me
Even though its an old question, I think its worth to answer. I struggled a lot to find a way to fetch user email address from linkedin using linkedin-j-android library. Unfortunately I could not find any ready to use solution, so I made changes in the library sources and re-packaged it to use in my app. You can download the library from this link:
https://dl.dropboxusercontent.com/u/46373731/linkedin-j-android.jar
You can use ProfileField.EMAIL_ADDRESS to fetch email-address.
I have been working with GSON to try and parse a Json response I am getting from a CakePHP server for about a week. Here is what the response looks like :
[{"BaseObject": {"field1":"1","field2":"1639","field3":"10","field4":"1","field5":"12","field6":"10.765984","field7":"-25.768357","field8":"1327790850"}},{"BaseObject":{"field1":"2","field2":"1934","field3":"19","field4":"30","field5":"2","field6":"10.758662","field7":"-25.769684","field8":"1327790850"}},{"BaseObject":{"field1":"3","field2":"2567","field3":"33","field4":"6","field5":"98","field6":"10.758786","field7":"-25.769843","field8":"1327790850"}},{"BaseObject":{"field1":"4","field2":"0","field3":"33","field4":"7","field5":"0","field6":"10.758786","field7":"-20.769843","field8":"1327790850"}},{"BaseObject":{"field1":"5","field2":"1097","field3":"33","field4":"1","field5":"0","field6":"15.758786","field7":"50.769843","field8":"1327790850"}},{"BaseObject":{"field1":"6","field2":"1936","field3":"50","field4":"0","field5":"9","field6":"19.234987","field7":"-67.340065","field8":"1327798560"}}]
I used a plugin for Notepad++ to verify that the response is valid Json and it is.
First I tried this function:
public static List<BaseObject> parserInputStreamGson(InputStream stream)
{
List<BaseObject> objList = new ArrayList<BaseObject>();
if(stream != null){
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG,"Trying to Parse Reader");
try{
objList = gson.fromJson(r, new TypeToken<List<BaseObject>>() {}.getType() );
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage() );
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage() );
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage() );
}
}
}
Log.d(TAG,"BaseObject[] = " + objList.toString());
return objList;
}
Then I tried this function:
public static BaseObject[] parserInputStreamGsonArray(InputStream stream)
{
BaseObject[] objectArray = null;
if (stream != null) {
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG, "Trying to Parse Reader");
try {
objectArray = gson.fromJson(r, new TypeToken<Event[]>() {}.getType());
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage());
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage());
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage());
}
}
}
if(eventArray != null){
for(int m=0;m<eventArray.length;m++){
Log.d(TAG, "objectArray[" + String.valueOf(m) + "] = " + objectArray[m].toString());
}
}
return objectArray;
}
And in both cases Gson returned 5 objects, but all of the fields were set to zero.
Finally I got this function to work, but it feels clunky.
public static List<BaseObject> ParseInputStream(InputStream stream) {
Reader r = new InputStreamReader(stream);
List<BaseObject> baseObjectList = new ArrayList<BaseObject>();
try {
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(r).getAsJsonArray();
JsonObject topObject = new JsonObject();
JsonObject subObject = new JsonObject();
for (int m = 0; m < array.size(); m++) {
if (array.get(m).isJsonObject()) {
topObject = array.get(m).getAsJsonObject();
if (topObject.get("BaseObject").isJsonObject()) {
subObject = topObject.get("BaseObject").getAsJsonObject();
BaseObject baseobject = new BaseObject();
baseobject.field1 = subObject.get("field1").getAsLong();
baseobject.field2 = subObject.get("field2").getAsInt();
baseobject.field3 = subObject.get("field3").getAsLong();
baseobject.field4 = subObject.get("field4").getAsInt();
baseobject.field5 = subObject.get("field5").getAsInt();
baseobject.field6 = subObject.get("field6").getAsDouble();
baseobject.field7 = subObject.get("field7").getAsDouble();
baseobject.field8 = subObject.get("field8").getAsLong();
baseObjectList.add(baseobject);
} else {
Log.e(TAG, "topObject[" + String.valueOf(m)+ "].subObject is not a JsonObject");
}
} else {
Log.e(TAG, "Array # " + String.valueOf(m)+ " is not a JsonObject!");
}
}
} catch (Exception ex) {
Log.e(TAG, "Exception thrown = " + ex.toString());
ex.printStackTrace();
}
return baseObjectList;
}
Here is the class I created for BaseObject.
public class BaseObject {
#SerializedName("field1")
public long field1;
#SerializedName("field2")
public int field2;
#SerializedName("field3")
public long field3;
#SerializedName("field4")
public int field4;
#SerializedName("field5")
public int field5;
#SerializedName("field6")
public double field6;
#SerializedName("field7")
public double field7;
#SerializedName("field8")
public long field8;
#Override
public String toString() {
return "(" +
"field1= " + String.valueOf(this.field1) + ", " +
"field2= " + String.valueOf(this.field2) + ", " +
"field3= " + String.valueOf(this.field3) + ", " +
"field4= " + String.valueOf(this.field4) + ", " +
"field5= " + String.valueOf(this.field5) + ", " +
"field6= " + String.valueOf(this.field6) + ", " +
"field7= " + String.valueOf(this.field7) + ", " +
"field8= " + String.valueOf(this.field8) +
")";
}
}
Can anyone tell me how I need to structure my data classes in order use Gson.fromJson to work.
Since your response is actually List<BaseObject>, you should be using
List baseObjectList = new Gson().fromJson(r,new TypeToken>() {}.getType())
Also I should mention that, you do not really need to use the #SerializedName annotations since your attribute names in the json reply and in the class are same.
UPDATE:
Oops.. Sorry, I should have tried your code before answering. Please refer to the following code. Everything boiled down to the Structuring of classes.
public class Sample {
public static class Wrapper{
private BaseObject BaseObject;
#Override
public String toString() {
return BaseObject == null? null : BaseObject.toString();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String json = "[{\"BaseObject\": {\"field1\":\"1\",\"field2\":\"1639\",\"field3\":\"10\",\"field4\":\"1\",\"field5\":\"12\",\"field6\":\"10.765984\",\"field7\":\"-25.768357\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"2\",\"field2\":\"1934\",\"field3\":\"19\",\"field4\":\"30\",\"field5\":\"2\",\"field6\":\"10.758662\",\"field7\":\"-25.769684\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"3\",\"field2\":\"2567\",\"field3\":\"33\",\"field4\":\"6\",\"field5\":\"98\",\"field6\":\"10.758786\",\"field7\":\"-25.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"4\",\"field2\":\"0\",\"field3\":\"33\",\"field4\":\"7\",\"field5\":\"0\",\"field6\":\"10.758786\",\"field7\":\"-20.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"5\",\"field2\":\"1097\",\"field3\":\"33\",\"field4\":\"1\",\"field5\":\"0\",\"field6\":\"15.758786\",\"field7\":\"50.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"6\",\"field2\":\"1936\",\"field3\":\"50\",\"field4\":\"0\",\"field5\":\"9\",\"field6\":\"19.234987\",\"field7\":\"-67.340065\",\"field8\":\"1327798560\"}}]";
List<Wrapper> results = new Gson().fromJson(json,new TypeToken<List<Wrapper>>(){}.getType());
System.out.println(results);
}
}
Just curious, do you have the liberty to change the JSON reply coming from server? IMHO, Its structure is a little complicated.
How to programmatically create and read WEP/EAP WiFi configurations in Android?
I have seen a number of people struggling on this very question on various forums and all across the community. I know this is not that straight forward(especially EAP) to figure out because When I wanted to achieve the same I too struggled quite a lot.Well, all the hard work of code analysis and searching various implementations on the internet done with I was finally able to achieve the goal. All the credit goes to number of open source projects and their developers.
I would like to share this knowledge with all, Since SO encourages this: "It's also perfectly fine to ask and answer your own question, as long as you pretend you're on Jeopardy: phrase it in the form of a question."
Part 1: Creating a WEP WiFi configuration programmatically.
Part 2: Read a WEP WiFi configuration programmatically.
Part 3: Read a EAP WiFi Configuration programmatically.
Part 4: Save a EAP WiFi configuration programmatically.
Part 1: Creating a WEP WiFi configuration programmatically
This is pretty much straightforward, WifiConfiguration exposes the interface to create the same. Here is the sample code:
void saveWepConfig()
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"SSID_NAME\""; //IMP! This should be in Quotes!!
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.wepKeys[0] = "\"aaabbb1234\""; //This is the WEP Password
wc.wepTxKeyIndex = 0;
WifiManager wifiManag = (WifiManager) this.getSystemService(WIFI_SERVICE);
boolean res1 = wifiManag.setWifiEnabled(true);
int res = wifi.addNetwork(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 );
}
Following the permissions needed in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE">
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE">
</uses-permission>
Part 2: Read a WEP WiFi configuration programmatically
Straighforward again. Here is the sample code:
void readWepConfig()
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> item = wifi.getConfiguredNetworks();
int i = item.size();
Log.d("WifiPreference", "NO OF CONFIG " + i );
Iterator<WifiConfiguration> iter = item.iterator();
WifiConfiguration config = item.get(0);
Log.d("WifiPreference", "SSID" + config.SSID);
Log.d("WifiPreference", "PASSWORD" + config.preSharedKey);
Log.d("WifiPreference", "ALLOWED ALGORITHMS");
Log.d("WifiPreference", "LEAP" + config.allowedAuthAlgorithms.get(AuthAlgorithm.LEAP));
Log.d("WifiPreference", "OPEN" + config.allowedAuthAlgorithms.get(AuthAlgorithm.OPEN));
Log.d("WifiPreference", "SHARED" + config.allowedAuthAlgorithms.get(AuthAlgorithm.SHARED));
Log.d("WifiPreference", "GROUP CIPHERS");
Log.d("WifiPreference", "CCMP" + config.allowedGroupCiphers.get(GroupCipher.CCMP));
Log.d("WifiPreference", "TKIP" + config.allowedGroupCiphers.get(GroupCipher.TKIP));
Log.d("WifiPreference", "WEP104" + config.allowedGroupCiphers.get(GroupCipher.WEP104));
Log.d("WifiPreference", "WEP40" + config.allowedGroupCiphers.get(GroupCipher.WEP40));
Log.d("WifiPreference", "KEYMGMT");
Log.d("WifiPreference", "IEEE8021X" + config.allowedKeyManagement.get(KeyMgmt.IEEE8021X));
Log.d("WifiPreference", "NONE" + config.allowedKeyManagement.get(KeyMgmt.NONE));
Log.d("WifiPreference", "WPA_EAP" + config.allowedKeyManagement.get(KeyMgmt.WPA_EAP));
Log.d("WifiPreference", "WPA_PSK" + config.allowedKeyManagement.get(KeyMgmt.WPA_PSK));
Log.d("WifiPreference", "PairWiseCipher");
Log.d("WifiPreference", "CCMP" + config.allowedPairwiseCiphers.get(PairwiseCipher.CCMP));
Log.d("WifiPreference", "NONE" + config.allowedPairwiseCiphers.get(PairwiseCipher.NONE));
Log.d("WifiPreference", "TKIP" + config.allowedPairwiseCiphers.get(PairwiseCipher.TKIP));
Log.d("WifiPreference", "Protocols");
Log.d("WifiPreference", "RSN" + config.allowedProtocols.get(Protocol.RSN));
Log.d("WifiPreference", "WPA" + config.allowedProtocols.get(Protocol.WPA));
Log.d("WifiPreference", "WEP Key Strings");
String[] wepKeys = config.wepKeys;
Log.d("WifiPreference", "WEP KEY 0" + wepKeys[0]);
Log.d("WifiPreference", "WEP KEY 1" + wepKeys[1]);
Log.d("WifiPreference", "WEP KEY 2" + wepKeys[2]);
Log.d("WifiPreference", "WEP KEY 3" + wepKeys[3]);
}
Part 3: Read a EAP WiFi Configuration programmatically
Now this is tricky. You can find the code which saves a EAP WiFi configuration through the vanilla Android UI in WifiDialog.java. Well easy enough We can use the same code in our Application, Well NO! If you happen to try this you will get errors saying cannot find the symbols eap, phase, client_cert and so on. A little detailed investigation tells us EnterpriseFieldis private inside WiFiConfiguration class and all the symbols we cannot find are of the type EnterpriseField. Well we've hit a roadblock, We need these fields for reading/saving a EAP config but we don't have programmatic access to them!
Java Reflection API to the rescue
Well I am not a Java expert so I wont be getting in to details of Reflection API as such and you can google for tutorials or get more information here.
To keep it Short and Sweet, Reflection API allows you to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.And, Importantly Reflection can help you access private data members inside a class Well this is what we need don't we? :)
Let's check the code example now which shows how to read a EAP WiFi configuration using Reflection Api. As a bonus the snippet will log the config to a file and save it on the SD Card....pretty slick ..eh ;) A little bit of overview of Reflection Api and I am sure grasping the code below is easy.
private static final String INT_PRIVATE_KEY = "private_key";
private static final String INT_PHASE2 = "phase2";
private static final String INT_PASSWORD = "password";
private static final String INT_IDENTITY = "identity";
private static final String INT_EAP = "eap";
private static final String INT_CLIENT_CERT = "client_cert";
private static final String INT_CA_CERT = "ca_cert";
private static final String INT_ANONYMOUS_IDENTITY = "anonymous_identity";
final String INT_ENTERPRISEFIELD_NAME = "android.net.wifi.WifiConfiguration$EnterpriseField";
This is the code to create a logfile on to SD card before calling the readEapConfig() function.
BufferedWriter out = null;
try
{
File root = Environment.getExternalStorageDirectory();
Toast toast = Toast.makeText(this, "SD CARD mounted and writable? " + root.canWrite(), 5000);
toast.show();
if (root.canWrite())
{
File gpxfile = new File(root, "ReadConfigLog.txt");
FileWriter gpxwriter = new FileWriter(gpxfile);
out = new BufferedWriter(gpxwriter);
out.write("Hello world");
//out.close();
}
} catch (IOException e)
{
Toast toast = Toast.makeText(this, "Problem reading SD CARD", 3000);
Toast toast2 = Toast.makeText(this, "Please take logs using Logcat", 5000);
Log.e("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "Could not write file " + e.getMessage());
}
Now the readEapConfig() function itself:
void readEapConfig(BufferedWriter out)
{
/*Get the WifiService */
WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE);
/*Get All WIfi configurations*/
List<WifiConfiguration> configList = wifi.getConfiguredNetworks();
/*Now we need to search appropriate configuration i.e. with name SSID_Name*/
for(int i = 0;i<configList.size();i++)
{
if(configList.get(i).SSID.contentEquals("\"SSID_NAME\""))
{
/*We found the appropriate config now read all config details*/
Iterator<WifiConfiguration> iter = configList.iterator();
WifiConfiguration config = configList.get(i);
/*I dont think these fields have anything to do with EAP config but still will
* print these to be on safe side*/
try {
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[SSID]" + config.SSID);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[SSID]" + config.SSID);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[BSSID]" + config.BSSID);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" +"[BSSID]" + config.BSSID);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[HIDDEN SSID]" + config.hiddenSSID);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[HIDDEN SSID]" + config.hiddenSSID);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[PASSWORD]" + config.preSharedKey);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>"+ "[PASSWORD]" + config.preSharedKey);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[ALLOWED ALGORITHMS]");
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>"+ "[ALLOWED ALGORITHMS]");
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[LEAP]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.LEAP));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[LEAP]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.LEAP));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[OPEN]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.OPEN));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[OPEN]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.OPEN));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[SHARED]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.SHARED));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[SHARED]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.SHARED));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[GROUP CIPHERS]");
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[GROUP CIPHERS]");
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[CCMP]" + config.allowedGroupCiphers.get(GroupCipher.CCMP));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[CCMP]" + config.allowedGroupCiphers.get(GroupCipher.CCMP));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" , "[TKIP]" + config.allowedGroupCiphers.get(GroupCipher.TKIP));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>"+ "[TKIP]" + config.allowedGroupCiphers.get(GroupCipher.TKIP));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WEP104]" + config.allowedGroupCiphers.get(GroupCipher.WEP104));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WEP104]" + config.allowedGroupCiphers.get(GroupCipher.WEP104));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WEP40]" + config.allowedGroupCiphers.get(GroupCipher.WEP40));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WEP40]" + config.allowedGroupCiphers.get(GroupCipher.WEP40));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[KEYMGMT]");
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[KEYMGMT]");
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[IEEE8021X]" + config.allowedKeyManagement.get(KeyMgmt.IEEE8021X));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>"+ "[IEEE8021X]" + config.allowedKeyManagement.get(KeyMgmt.IEEE8021X));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[NONE]" + config.allowedKeyManagement.get(KeyMgmt.NONE));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[NONE]" + config.allowedKeyManagement.get(KeyMgmt.NONE));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WPA_EAP]" + config.allowedKeyManagement.get(KeyMgmt.WPA_EAP));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WPA_EAP]" + config.allowedKeyManagement.get(KeyMgmt.WPA_EAP));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WPA_PSK]" + config.allowedKeyManagement.get(KeyMgmt.WPA_PSK));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WPA_PSK]" + config.allowedKeyManagement.get(KeyMgmt.WPA_PSK));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[PairWiseCipher]");
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[PairWiseCipher]");
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[CCMP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.CCMP));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[CCMP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.CCMP));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[NONE]" + config.allowedPairwiseCiphers.get(PairwiseCipher.NONE));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[NONE]" + config.allowedPairwiseCiphers.get(PairwiseCipher.NONE));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[TKIP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.TKIP));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[TKIP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.TKIP));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[Protocols]");
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[Protocols]");
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[RSN]" + config.allowedProtocols.get(Protocol.RSN));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[RSN]" + config.allowedProtocols.get(Protocol.RSN));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WPA]" + config.allowedProtocols.get(Protocol.WPA));
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WPA]" + config.allowedProtocols.get(Protocol.WPA));
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[PRE_SHARED_KEY]" + config.preSharedKey);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[PRE_SHARED_KEY]" + config.preSharedKey);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WEP Key Strings]");
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WEP Key Strings]");
String[] wepKeys = config.wepKeys;
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WEP KEY 0]" + wepKeys[0]);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WEP KEY 0]" + wepKeys[0]);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WEP KEY 1]" + wepKeys[1]);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WEP KEY 1]" + wepKeys[1]);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WEP KEY 2]" + wepKeys[2]);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WEP KEY 2]" + wepKeys[2]);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[WEP KEY 3]" + wepKeys[3]);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[WEP KEY 3]" + wepKeys[3]);
}
catch(IOException e)
{
Toast toast1 = Toast.makeText(this, "Failed to write Logs to ReadConfigLog.txt", 3000);
Toast toast2 = Toast.makeText(this, "Please take logs using Logcat", 5000);
Log.e("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "Could not write to ReadConfigLog.txt" + e.getMessage());
}
/*reflection magic*/
/*These are the fields we are really interested in*/
try
{
// Let the magic start
Class[] wcClasses = WifiConfiguration.class.getClasses();
// null for overzealous java compiler
Class wcEnterpriseField = null;
for (Class wcClass : wcClasses)
if (wcClass.getName().equals(INT_ENTERPRISEFIELD_NAME))
{
wcEnterpriseField = wcClass;
break;
}
boolean noEnterpriseFieldType = false;
if(wcEnterpriseField == null)
noEnterpriseFieldType = true; // Cupcake/Donut access enterprise settings directly
Field wcefAnonymousId = null, wcefCaCert = null, wcefClientCert = null, wcefEap = null, wcefIdentity = null, wcefPassword = null, wcefPhase2 = null, wcefPrivateKey = null;
Field[] wcefFields = WifiConfiguration.class.getFields();
// Dispatching Field vars
for (Field wcefField : wcefFields)
{
if (wcefField.getName().trim().equals(INT_ANONYMOUS_IDENTITY))
wcefAnonymousId = wcefField;
else if (wcefField.getName().trim().equals(INT_CA_CERT))
wcefCaCert = wcefField;
else if (wcefField.getName().trim().equals(INT_CLIENT_CERT))
wcefClientCert = wcefField;
else if (wcefField.getName().trim().equals(INT_EAP))
wcefEap = wcefField;
else if (wcefField.getName().trim().equals(INT_IDENTITY))
wcefIdentity = wcefField;
else if (wcefField.getName().trim().equals(INT_PASSWORD))
wcefPassword = wcefField;
else if (wcefField.getName().trim().equals(INT_PHASE2))
wcefPhase2 = wcefField;
else if (wcefField.getName().trim().equals(INT_PRIVATE_KEY))
wcefPrivateKey = wcefField;
}
Method wcefValue = null;
if(!noEnterpriseFieldType)
{
for(Method m: wcEnterpriseField.getMethods())
//System.out.println(m.getName());
if(m.getName().trim().equals("value")){
wcefValue = m;
break;
}
}
/*EAP Method*/
String result = null;
Object obj = null;
if(!noEnterpriseFieldType)
{
obj = wcefValue.invoke(wcefEap.get(config), null);
String retval = (String)obj;
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP METHOD]" + retval);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP METHOD]" + retval);
}
else
{
obj = wcefEap.get(config);
String retval = (String)obj;
}
/*phase 2*/
if(!noEnterpriseFieldType)
{
result = (String) wcefValue.invoke(wcefPhase2.get(config), null);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP PHASE 2 AUTHENTICATION]" + result);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP PHASE 2 AUTHENTICATION]" + result);
}
else
{
result = (String) wcefPhase2.get(config);
}
/*Anonymous Identity*/
if(!noEnterpriseFieldType)
{
result = (String) wcefValue.invoke(wcefAnonymousId.get(config),null);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP ANONYMOUS IDENTITY]" + result);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP ANONYMOUS IDENTITY]" + result);
}
else
{
result = (String) wcefAnonymousId.get(config);
}
/*CA certificate*/
if(!noEnterpriseFieldType)
{
result = (String) wcefValue.invoke(wcefCaCert.get(config), null);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP CA CERTIFICATE]" + result);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP CA CERTIFICATE]" + result);
}
else
{
result = (String)wcefCaCert.get(config);
}
/*private key*/
if(!noEnterpriseFieldType)
{
result = (String) wcefValue.invoke(wcefPrivateKey.get(config),null);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP PRIVATE KEY]" + result);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP PRIVATE KEY]" + result);
}
else
{
result = (String)wcefPrivateKey.get(config);
}
/*Identity*/
if(!noEnterpriseFieldType)
{
result = (String) wcefValue.invoke(wcefIdentity.get(config), null);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP IDENTITY]" + result);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP IDENTITY]" + result);
}
else
{
result = (String)wcefIdentity.get(config);
}
/*Password*/
if(!noEnterpriseFieldType)
{
result = (String) wcefValue.invoke(wcefPassword.get(config), null);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP PASSWORD]" + result);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP PASSWORD]" + result);
}
else
{
result = (String)wcefPassword.get(config);
}
/*client certificate*/
if(!noEnterpriseFieldType)
{
result = (String) wcefValue.invoke(wcefClientCert.get(config), null);
Log.d("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "[EAP CLIENT CERT]" + result);
out.write("<<<<<<<<<<WifiPreference>>>>>>>>>>>>" + "[EAP CLIENT CERT]" + result);
Toast toast1 = Toast.makeText(this, "All config data logged to ReadConfigLog.txt", 3000);
Toast toast2 = Toast.makeText(this, "Extract ReadConfigLog.txt from SD CARD", 5000);
}
else
{
result = (String)wcefClientCert.get(config);
}
out.close();
}
catch(IOException e)
{
Toast toast1 = Toast.makeText(this, "Failed to write Logs to ReadConfigLog.txt", 3000);
Toast toast2 = Toast.makeText(this, "Please take logs using Logcat", 5000);
Log.e("<<<<<<<<<<WifiPreference>>>>>>>>>>>>", "Could not write to ReadConfigLog.txt" + e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Ahh I ran out of edit space, Adding the remaining part here.
Part 4: Save a EAP WiFi configuration programmatically
If you already read the part 3, you already understand the Reflection magic that works here, If you are directly jumping to this section please read the introduction before the code snippet in part 3 and you will be up to speed to breeze through the code here!
void saveEapConfig(String passString, String userName)
{
/********************************Configuration Strings****************************************************/
final String ENTERPRISE_EAP = "TLS";
final String ENTERPRISE_CLIENT_CERT = "keystore://USRCERT_CertificateName";
final String ENTERPRISE_PRIV_KEY = "USRPKEY_CertificateName";
//CertificateName = Name given to the certificate while installing it
/*Optional Params- My wireless Doesn't use these*/
final String ENTERPRISE_PHASE2 = "";
final String ENTERPRISE_ANON_IDENT = "ABC";
final String ENTERPRISE_CA_CERT = ""; // If required: "keystore://CACERT_CaCertificateName"
/********************************Configuration Strings****************************************************/
/*Create a WifiConfig*/
WifiConfiguration selectedConfig = new WifiConfiguration();
/*AP Name*/
selectedConfig.SSID = "\"SSID_Name\"";
/*Priority*/
selectedConfig.priority = 40;
/*Enable Hidden SSID*/
selectedConfig.hiddenSSID = true;
/*Key Mgmnt*/
selectedConfig.allowedKeyManagement.clear();
selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
/*Group Ciphers*/
selectedConfig.allowedGroupCiphers.clear();
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
/*Pairwise ciphers*/
selectedConfig.allowedPairwiseCiphers.clear();
selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
/*Protocols*/
selectedConfig.allowedProtocols.clear();
selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
// Enterprise Settings
// Reflection magic here too, need access to non-public APIs
try {
// Let the magic start
Class[] wcClasses = WifiConfiguration.class.getClasses();
// null for overzealous java compiler
Class wcEnterpriseField = null;
for (Class wcClass : wcClasses)
if (wcClass.getName().equals(INT_ENTERPRISEFIELD_NAME))
{
wcEnterpriseField = wcClass;
break;
}
boolean noEnterpriseFieldType = false;
if(wcEnterpriseField == null)
noEnterpriseFieldType = true; // Cupcake/Donut access enterprise settings directly
Field wcefAnonymousId = null, wcefCaCert = null, wcefClientCert = null, wcefEap = null, wcefIdentity = null, wcefPassword = null, wcefPhase2 = null, wcefPrivateKey = null, wcefEngine = null, wcefEngineId = null;
Field[] wcefFields = WifiConfiguration.class.getFields();
// Dispatching Field vars
for (Field wcefField : wcefFields)
{
if (wcefField.getName().equals(INT_ANONYMOUS_IDENTITY))
wcefAnonymousId = wcefField;
else if (wcefField.getName().equals(INT_CA_CERT))
wcefCaCert = wcefField;
else if (wcefField.getName().equals(INT_CLIENT_CERT))
wcefClientCert = wcefField;
else if (wcefField.getName().equals(INT_EAP))
wcefEap = wcefField;
else if (wcefField.getName().equals(INT_IDENTITY))
wcefIdentity = wcefField;
else if (wcefField.getName().equals(INT_PASSWORD))
wcefPassword = wcefField;
else if (wcefField.getName().equals(INT_PHASE2))
wcefPhase2 = wcefField;
else if (wcefField.getName().equals(INT_PRIVATE_KEY))
wcefPrivateKey = wcefField;
else if (wcefField.getName().equals("engine"))
wcefEngine = wcefField;
else if (wcefField.getName().equals("engine_id"))
wcefEngineId = wcefField;
}
Method wcefSetValue = null;
if(!noEnterpriseFieldType){
for(Method m: wcEnterpriseField.getMethods())
//System.out.println(m.getName());
if(m.getName().trim().equals("setValue"))
wcefSetValue = m;
}
/*EAP Method*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefEap.get(selectedConfig), ENTERPRISE_EAP);
}
else
{
wcefEap.set(selectedConfig, ENTERPRISE_EAP);
}
/*EAP Phase 2 Authentication*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefPhase2.get(selectedConfig), ENTERPRISE_PHASE2);
}
else
{
wcefPhase2.set(selectedConfig, ENTERPRISE_PHASE2);
}
/*EAP Anonymous Identity*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefAnonymousId.get(selectedConfig), ENTERPRISE_ANON_IDENT);
}
else
{
wcefAnonymousId.set(selectedConfig, ENTERPRISE_ANON_IDENT);
}
/*EAP CA Certificate*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefCaCert.get(selectedConfig), ENTERPRISE_CA_CERT);
}
else
{
wcefCaCert.set(selectedConfig, ENTERPRISE_CA_CERT);
}
/*EAP Private key*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefPrivateKey.get(selectedConfig), ENTERPRISE_PRIV_KEY);
}
else
{
wcefPrivateKey.set(selectedConfig, ENTERPRISE_PRIV_KEY);
}
/*EAP Identity*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefIdentity.get(selectedConfig), userName);
}
else
{
wcefIdentity.set(selectedConfig, userName);
}
/*EAP Password*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefPassword.get(selectedConfig), passString);
}
else
{
wcefPassword.set(selectedConfig, passString);
}
/*EAp Client certificate*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefClientCert.get(selectedConfig), ENTERPRISE_CLIENT_CERT);
}
else
{
wcefClientCert.set(selectedConfig, ENTERPRISE_CLIENT_CERT);
}
/*Engine fields*/
if(!noEnterpriseFieldType)
{
wcefSetValue.invoke(wcefEngine.get(wifiConf), "1");
wcefSetValue.invoke(wcefEngineId.get(wifiConf), "keystore");
}
// Adhoc for CM6
// if non-CM6 fails gracefully thanks to nested try-catch
try{
Field wcAdhoc = WifiConfiguration.class.getField("adhocSSID");
Field wcAdhocFreq = WifiConfiguration.class.getField("frequency");
//wcAdhoc.setBoolean(selectedConfig, prefs.getBoolean(PREF_ADHOC,
// false));
wcAdhoc.setBoolean(selectedConfig, false);
int freq = 2462; // default to channel 11
//int freq = Integer.parseInt(prefs.getString(PREF_ADHOC_FREQUENCY,
//"2462")); // default to channel 11
//System.err.println(freq);
wcAdhocFreq.setInt(selectedConfig, freq);
} catch (Exception e)
{
e.printStackTrace();
}
} catch (Exception e)
{
// TODO Auto-generated catch block
// FIXME As above, what should I do here?
e.printStackTrace();
}
WifiManager wifiManag = (WifiManager) getSystemService(Context.WIFI_SERVICE);
boolean res1 = wifiManag.setWifiEnabled(true);
int res = wifiManag.addNetwork(selectedConfig);
Log.d("WifiPreference", "add Network returned " + res );
boolean b = wifiManag.enableNetwork(selectedConfig.networkId, false);
Log.d("WifiPreference", "enableNetwork returned " + b );
boolean c = wifiManag.saveConfiguration();
Log.d("WifiPreference", "Save configuration returned " + c );
boolean d = wifiManag.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + d );
}
Well thats it! And I hope this helps some lost developer, somewhere, sometime :)
Android has added an API to JellyBean 4.3. You must use this option if you want to configure WIFI on API 18:
http://developer.android.com/reference/android/net/wifi/WifiEnterpriseConfig.html
Part 4 started me off on the right path! However i wanted to create a TTLS rather than TLS config here is how i did it!
/********************************Configuration Strings****************************************************/
final String ENTERPRISE_EAP = "TTLS";
/*Optional Params- My wireless Doesn't use these*/
final String ENTERPRISE_PHASE2 = "PAP";
final String ENTERPRISE_ANON_IDENT = "ABC";
final String ENTERPRISE_CA_CERT = "";
/********************************Configuration Strings****************************************************/
/*Create a WifiConfig*/
WifiConfiguration selectedConfig = new WifiConfiguration();
/*AP Name*/
selectedConfig.SSID = "\"EAP_SSID_TEST_CONFIG\"";
/*Priority*/
selectedConfig.priority = 40;
/*Enable Hidden SSID*/
selectedConfig.hiddenSSID = false;
/*Key Mgmnt*/
selectedConfig.allowedKeyManagement.clear();
selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
/*Group Ciphers*/
selectedConfig.allowedGroupCiphers.clear();
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
/*Pairwise ciphers*/
selectedConfig.allowedPairwiseCiphers.clear();
selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
/*Protocols*/
selectedConfig.allowedProtocols.clear();
selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
// Enterprise Settings
// Reflection magic here too, need access to non-public APIs
try {
// Let the magic start
Class[] wcClasses = WifiConfiguration.class.getClasses();
// null for overzealous java compiler
Class wcEnterpriseField = null;
for (Class wcClass : wcClasses)
if (wcClass.getName().equals(INT_ENTERPRISEFIELD_NAME))
{
wcEnterpriseField = wcClass;
break;
}
boolean noEnterpriseFieldType = false;
if(wcEnterpriseField == null)
noEnterpriseFieldType = true; // Cupcake/Donut access enterprise settings directly
Field wcefAnonymousId = null, wcefCaCert = null, wcefClientCert = null, wcefEap = null, wcefIdentity = null, wcefPassword = null, wcefPhase2 = null, wcefPrivateKey = null;
Field[] wcefFields = WifiConfiguration.class.getFields();
// Dispatching Field vars
for (Field wcefField : wcefFields)
{
if (wcefField.getName().equals(INT_ANONYMOUS_IDENTITY))
wcefAnonymousId = wcefField;
else if (wcefField.getName().equals(INT_CA_CERT))
wcefCaCert = wcefField;
else if (wcefField.getName().equals(INT_CLIENT_CERT))
wcefClientCert = wcefField;
else if (wcefField.getName().equals(INT_EAP))
wcefEap = wcefField;
else if (wcefField.getName().equals(INT_IDENTITY))
wcefIdentity = wcefField;
else if (wcefField.getName().equals(INT_PASSWORD))
wcefPassword = wcefField;
else if (wcefField.getName().equals(INT_PHASE2))
wcefPhase2 = wcefField;
else if (wcefField.getName().equals(INT_PRIVATE_KEY))
wcefPrivateKey = wcefField;
}
Method wcefSetValue = null;
if(!noEnterpriseFieldType){
for(Method m: wcEnterpriseField.getMethods())
//System.out.println(m.getName());
if(m.getName().trim().equals("setValue"))
wcefSetValue = m;
}
/*EAP Method*/
if(!noEnterpriseFieldType){
wcefSetValue.invoke(wcefEap.get(selectedConfig), ENTERPRISE_EAP);
}
/*EAP Phase 2 Authentication*/
if(!noEnterpriseFieldType){
wcefSetValue.invoke(wcefPhase2.get(selectedConfig), ENTERPRISE_PHASE2);
}
/*EAP Anonymous Identity*/
if(!noEnterpriseFieldType){
wcefSetValue.invoke(wcefAnonymousId.get(selectedConfig), ENTERPRISE_ANON_IDENT);
}
/*EAP CA Certificate*/
if(!noEnterpriseFieldType){
wcefSetValue.invoke(wcefCaCert.get(selectedConfig), ENTERPRISE_CA_CERT);
}
/*EAP Identity*/
if(!noEnterpriseFieldType){
wcefSetValue.invoke(wcefIdentity.get(selectedConfig), "test user name");
}
/*EAP Password*/
if(!noEnterpriseFieldType){
wcefSetValue.invoke(wcefPassword.get(selectedConfig), "test password");
}
try{
} catch (Exception e)
{
e.printStackTrace();
}
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
WifiManager wifiManag = (WifiManager) getSystemService(Context.WIFI_SERVICE);
boolean res1 = wifiManag.setWifiEnabled(true);
int res = wifiManag.addNetwork(selectedConfig);
Log.d("WifiPreference", "add Network returned " + res );
// boolean b = wifiManag.enableNetwork(selectedConfig.networkId, false);
// Log.d("WifiPreference", "enableNetwork returned " + b );
// boolean c = wifiManag.saveConfiguration();
// Log.d("WifiPreference", "Save configuration returned " + c );
// boolean d = wifiManag.enableNetwork(res, true);
// Log.d("WifiPreference", "enableNetwork returned " + d );
}
Hope this helps some one.
#Android learner I removed the bit about adHocFrequency and SSID as they were causing crashes but my results were still good without them.
The WEP keys are masked, so it is not possible to read them with the mentioned code
Log.d("WifiPreference", "WEP KEY 0" + wepKeys[0]);
Log.d("WifiPreference", "WEP KEY 1" + wepKeys[1]);
Log.d("WifiPreference", "WEP KEY 2" + wepKeys[2]);
Log.d("WifiPreference", "WEP KEY 3" + wepKeys[3]);
Is there any way to solve this in same way as the EAP solution?
With reflection?