Gsm network info in android - android

Does someone know how to get gsm information in android? Information like BCCH (Broadcast Control Channel) and BCIS (Base Station Identity Code). I already got the LAC (Location Area Code) and CID (Cell ID). I know that is a low level information but does someone know to get those information? I am having a hard time researching and i don't have an idea about cellular network. Please Help thanks :)

Here is function which gives you complete information of gsm network.
just Call with context from your activity
private void getNWInfo(Context context) {
/**
* <uses-permission android:name="android.permission.READ_PHONE_STATE"
* /> <uses-permission
* android:name="android.permission.ACCESS_NETWORK_STATE"/>
*/
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = telephonyManager.getNetworkOperator();
int mcc = 0, mnc = 0;
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
}
String SimNumber = telephonyManager.getLine1Number();
String SimSerialNumber = telephonyManager.getSimSerialNumber();
String countryISO = telephonyManager.getSimCountryIso();
String operatorName = telephonyManager.getSimOperatorName();
String operator = telephonyManager.getSimOperator();
int simState = telephonyManager.getSimState();
String voicemailNumer = telephonyManager.getVoiceMailNumber();
String voicemailAlphaTag = telephonyManager.getVoiceMailAlphaTag();
// Getting connected network iso country code
String networkCountry = telephonyManager.getNetworkCountryIso();
// Getting the connected network operator ID
String networkOperatorId = telephonyManager.getNetworkOperator();
// Getting the connected network operator name
String networkName = telephonyManager.getNetworkOperatorName();
int networkType = telephonyManager.getNetworkType();
String network = "";
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (cm.getActiveNetworkInfo().getTypeName().equals("MOBILE"))
network = "Cell Network/3G";
else if (cm.getActiveNetworkInfo().getTypeName().equals("WIFI"))
network = "WiFi";
else
network = "N/A";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("network :" + network +
"\n" + "countryISO : " + countryISO + "\n" + "operatorName : "
+ operatorName + "\n" + "operator : " + operator + "\n"
+ "simState :" + simState + "\n" + "Sim Serial Number : "
+ SimSerialNumber + "\n" + "Sim Number : " + SimNumber + "\n"
+ "Voice Mail Numer" + voicemailNumer + "\n"
+ "Voice Mail Alpha Tag" + voicemailAlphaTag + "\n"
+ "Sim State" + simState + "\n" + "Mobile Country Code MCC : "
+ mcc + "\n" + "Mobile Network Code MNC : " + mnc + "\n"
+ "Network Country : " + networkCountry + "\n"
+ "Network OperatorId : " + networkOperatorId + "\n"
+ "Network Name : " + networkName + "\n" + "Network Type : "
+ networkType);
}
you can find more details on this blog
http://khurramitdeveloper.blogspot.in/search?updated-max=2013-11-07T03:23:00-08:00&max-results=7
hope it will help you :)

Please visit here. It explains that no APIs are available to get the Radio Information.

You can try this:
public static JSONArray getCellInfo(Context ctx){
TelephonyManager tel = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
JSONArray cellList = new JSONArray();
int phoneTypeInt = tel.getPhoneType();
String phoneType = "unknown";
if (phoneTypeInt == TelephonyManager.PHONE_TYPE_GSM)
phoneType = "gsm";
else if (phoneTypeInt == TelephonyManager.PHONE_TYPE_CDMA)
phoneType = "cdma";
//from Android M up must use getAllCellInfo
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
List<NeighboringCellInfo> neighCells = tel.getNeighboringCellInfo();
for (int i = 0; i < neighCells.size(); i++) {
try {
JSONObject cellObj = new JSONObject();
NeighboringCellInfo thisCell = neighCells.get(i);
cellObj.put("cellId", thisCell.getCid());
cellObj.put("lac", thisCell.getLac());
cellObj.put("rssi", thisCell.getRssi());
cellList.put(cellObj);
} catch (Exception e) {
}
}
} else {
List<CellInfo> infos = tel.getAllCellInfo();
for (int i = 0; i < infos.size(); ++i) {
try {
JSONObject cellObj = new JSONObject();
CellInfo info = infos.get(i);
if (info instanceof CellInfoGsm) {
CellSignalStrengthGsm gsm = ((CellInfoGsm) info).getCellSignalStrength();
CellIdentityGsm identityGsm = ((CellInfoGsm) info).getCellIdentity();
cellObj.put("cellId", identityGsm.getCid());
cellObj.put("lac", identityGsm.getLac());
cellObj.put("dbm", gsm.getDbm());
cellList.put(cellObj);
} else if (info instanceof CellInfoLte) {
CellSignalStrengthLte lte = ((CellInfoLte) info).getCellSignalStrength();
CellIdentityLte identityLte = ((CellInfoLte) info).getCellIdentity();
cellObj.put("cellId", identityLte.getCi());
cellObj.put("tac", identityLte.getTac());
cellObj.put("dbm", lte.getDbm());
cellList.put(cellObj);
}
} catch (Exception ex) {
}
}
}
return cellList;
}

Related

TelephonyManager.getAllCellInfo() return Null or displays Nothing

I'm facing an issue with getAllCellInfo().
App has permissions needed :
here is my code :
1- listener
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
2- Info from SignalStrength
TextView comparisonText = (TextView) findViewById(R.id.textViewComparison);
Object ssFieldValueRsrp = null;
Object ssFieldValueRsrq = null;
Object ssFieldValueRssnr = null;
Object ssFieldValueCqi=null;
try {
Field privateStringSsFieldRSRQ = SignalStrength.class.getDeclaredField("mLteRsrq");
Field privateStringSsFieldRSRP = SignalStrength.class.getDeclaredField("mLteRsrp");
Field privateStringSsFieldRssnr = SignalStrength.class.getDeclaredField("mLteRssnr");
Field privateStringSsFieldCqi = SignalStrength.class.getDeclaredField("mLteCqi");
privateStringSsFieldRSRQ.setAccessible(true);
ssFieldValueRsrq = privateStringSsFieldRSRQ.get(signalStrength);
privateStringSsFieldRSRP.setAccessible(true);
ssFieldValueRsrp = privateStringSsFieldRSRP.get(signalStrength);
privateStringSsFieldRssnr.setAccessible(true);
ssFieldValueRssnr = privateStringSsFieldRssnr.get(signalStrength);
privateStringSsFieldCqi.setAccessible(true);
ssFieldValueCqi = privateStringSsFieldCqi.get(signalStrength);
} catch (NoSuchFieldException ex) {
} catch (IllegalAccessException x) {
}
String ssRsrp = Integer.toString((int) ssFieldValueRsrp);
String ssRsrq = Integer.toString((int) ssFieldValueRsrq);
String ssRssnr = Integer.toString((int) ssFieldValueRssnr);
String ssCqi = Integer.toString((int) ssFieldValueCqi);
String headerString = "Info from \"SignalStrength\":";
SpannableString spannableHeaderString = new SpannableString(headerString);
spannableHeaderString.setSpan(new UnderlineSpan(), 0, spannableHeaderString.length(), 0);
comparisonText.setText(spannableHeaderString);
comparisonText.append
(
"\nRSRP: " + ssRsrp
+ "\nRSRQ: " + ssRsrq
+"\nCQI: "+ ssCqi
+"\nRSSNR: "+ ssRssnr
);
3- Info from CellSignalStrengthLte
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
List<android.telephony.CellInfo> infor = tm.getAllCellInfo();
for (android.telephony.CellInfo info : infor)
{
if (info instanceof CellInfoLte)
{
CellSignalStrengthLte ss = ((CellInfoLte) info).getCellSignalStrength();
//theButton.setText( ss.toString());
Object fieldValueRSRP = null;
Object fieldValueRSRQ = null;
Object fieldValueRssnr = null;
Object fieldValueCqi=null;
try
{
Field privateStringFieldRSRQ = CellSignalStrengthLte.class.getDeclaredField("mRsrq");
Field privateStringFieldRSRP = CellSignalStrengthLte.class.getDeclaredField("mRsrp");
Field privateStringFieldCqi = CellSignalStrengthLte.class.getDeclaredField("mCqi");
Field privateStringFieldRSSNR = CellSignalStrengthLte.class.getDeclaredField("mRssnr");
privateStringFieldRSRQ.setAccessible(true);
fieldValueRSRQ = privateStringFieldRSRQ.get(ss);
privateStringFieldRSRP.setAccessible(true);
fieldValueRSRP = privateStringFieldRSRP.get(ss);
privateStringFieldRSSNR.setAccessible(true);
fieldValueRssnr = privateStringFieldRSSNR.get(ss);
privateStringFieldCqi.setAccessible(true);
fieldValueCqi = privateStringFieldCqi.get(ss);
}
catch (NoSuchFieldException ex) {}
catch (IllegalAccessException x) {}
String rsrp = Integer.toString((int) fieldValueRSRP);
String rsrq = Integer.toString((int) fieldValueRSRQ);
String rssnr = Integer.toString((int) fieldValueRssnr);
String cqi = Integer.toString((int) fieldValueCqi);
headerString = "Info from \"CellSignalStrengthLte\":";
spannableHeaderString = new SpannableString(headerString);
spannableHeaderString.setSpan( new UnderlineSpan(), 0, spannableHeaderString.length(), 0);
theText.setText
(
"\nAltitude: " + loc.getAltitude() + "\n\n"+loc.getLongitude()+"\n\n"+loc.getLatitude()+"\n\n"
);
theText.append(spannableHeaderString);
theText.append
(
"\nRSRP: " + rsrp
+ "\nRSRQ: " + rsrq
+ "\nCQI: " + cqi
+ "\nRSSNR: " + rssnr
);
}
}
Huawei Y6II : marshmallow (android 6) :
App run smoothly but function skipped
Huawei Nova3i (android 9)
app crashes with null pointer on List<android.telephony.CellInfo> infor = tm.getAllCellInfo();
Samsun S10 (android 9)
app running perfectly
Resolved :
This issue is related to some dual SIM phones

Parse getAllcellinfo values from telephony manager

i'm using the following function to get Allcellinfo of an device network and im getting the values as an string now i need to parse it in order to get the CellSignalStrengthLte data how can i achieve it
//code
TelephonyManager tm = (TelephonyManager) Context.getSystemService(mContext.TELEPHONY_SERVICE);
List<CellInfo> cellInfos = tm.getAllCellInfo();
String data = cellInfos.get(0).toString();
Log.d("Info ", " "+data);
Result is
CellInfoLte:{mRegistered=YES mTimeStampType=oem_ril mTimeStamp=207387894126206ns CellIdentityLte:{ mMcc=405 mMnc=869 mCi=2971664 mPci=123 mTac=56} CellSignalStrengthLte: ss=25 rsrp=-91 rsrq=-7 rssnr=2147483647 cqi=2147483647 ta=2147483647}
How can parse this string to get details regaridng CellinfoLte,CellIdentityLte
I also noticed that CellinfoLTE and CellIdentityLTE is not so great at the moment, so I just wrote my own parsing class. Only tested this a few times, and didn't have problems, but more testing should display if additional future tweaking will be necessary.
Here's the class:
public class LTEStruct
{
public static final int UNKNOWN = Integer.MAX_VALUE; //Default value for unknown fields
public boolean isRegistered;
public long timeStamp;
public int MCC;
public int MNC;
public int CID;
public int PCI;
public int TAC;
public int SS;
public int RSRP;
public int RSRQ;
public int RSSNR;
public int CQI;
public int tAdvance;
Context mContext;
//Public constructor
public LTEStruct(Context context)
{
mContext = context; //not used at the moment but possibly for future function
}
public void parse(String inTest)
{
//get isRegistered
int index = inTest.indexOf("mRegistered=") + ("mRegistered=").length();
if(inTest.substring(index,index + 3).contains("YES"))
isRegistered = true;
else
isRegistered = false;
//getTimestamp
timeStamp = getValue(inTest,"mTimeStamp=", "ns");
//get Cell Identity paramters
MCC = (int) getValue(inTest,"mMcc=", " "); //get Mcc
MNC = (int) getValue(inTest,"mMnc=", " "); //get MNC
CID = (int) getValue(inTest,"mCi=", " "); //get CID
PCI = (int) getValue(inTest,"mPci="," "); //get PCI
TAC = (int) getValue(inTest,"mTac=","}"); //get TAC
//get RF related parameters
SS = (int) getValue(inTest," ss="," "); //get SS
RSRP = (int)getValue(inTest,"rsrp=", " "); //get RSRP
RSRQ = (int)getValue(inTest,"rsrq=", " "); //get RSRQ
RSSNR = (int)getValue(inTest,"rssnr=", " "); //get RSSNR
CQI = (int)getValue(inTest," cqi=", " "); //get CQI
tAdvance = (int)getValue(inTest," ta=", "}"); //get timing advance
}
//internal function to help with parsing of raw LTE strings
private long getValue(String fullS, String startS, String stopS)
{
int index = fullS.indexOf(startS) + (startS).length();
int endIndex = fullS.indexOf(stopS,index);
return Long.parseLong(fullS.substring(index,endIndex).trim());
}
}
So if I implement this very basically with the input LTE string:
//permission check
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions((Activity)this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
//get cell info
TelephonyManager tel = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
List<CellInfo> infos = tel.getAllCellInfo();
for (int i = 0; i<infos.size(); ++i)
{
try
{
CellInfo info = infos.get(i);
if (info instanceof CellInfoLte) {
LTEStruct lte = new LTEStruct(this);
lte.parse(info.toString());
//write out parsed results for what it's worth
Log.i("LTE parseOutput", "tAdvance: " + lte.tAdvance + "\r\nCQI: " + lte.CQI + "\r\nRSSNR: " + lte.RSSNR + "\r\nRSRP: " + lte.RSRP + "\r\nSS: " + lte.SS +
"\r\nCID: " + lte.CID + "\r\nTimestamp: " + lte.timeStamp + "\r\nTAC: " + lte.TAC + "\r\nPCI: " + lte.PCI + "\r\nMNC: " + lte.MNC + "\r\nMCC: " + lte.MCC + "\r\nRegistered: " + lte.isRegistered);
} else
Log.i("LTE testing", "not LTE cell info measured");
} catch (Exception ex) {
Log.i("neighboring error: ", ex.getMessage());
}
}
Hope it helps ;)

How to get neighbor cell info from getAllCellInfo?

this is the phone state listener i'm using to detect the changes
public PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
Log.d("SIGNAL ", " " + signalStrength.toString());
TelephonyManager tm = (TelephonyManager) mContext.getSystemService(mContext.TELEPHONY_SERVICE);
List<CellInfo> cellInfos = tm.getAllCellInfo();
for (int i=0 ;i<cellInfos.size() ;i++)
{
Log.d("test ",cellInfos.get(0).toString() );
}
}
};
The problem is currently i'm getting all cell information as below:
result - > logs CellInfoLte:{mRegistered=YES mTimeStampType=oem_ril
mTimeStamp=192908703241551ns CellIdentityLte:{ mMcc=405 mMnc=869
mCi=2971664 mPci=123 mTac=56} CellSignalStrengthLte: ss=27 rsrp=-90
rsrq=-10 rssnr=2147483647 cqi=2147483647 ta=2147483647}
How can i parse this to get CellInfoLte, CellIdentityLte and CellSignalStrengthLte from the above result
if you're still struggling with the problem, this is the method I'm using:
//permission check
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions((Activity)this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
String list = ""; //I'm just adding everything to a string to display, but you can do whatever
//get cell info
TelephonyManager tel = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
List<CellInfo> infos = tel.getAllCellInfo();
for (int i = 0; i<infos.size(); ++i)
{
try {
CellInfo info = infos.get(i);
if (info instanceof CellInfoGsm) //if GSM connection
{
list += "Site_"+i + "\r\n";
list += "Registered: " + info.isRegistered() + "\r\n";
CellSignalStrengthGsm gsm = ((CellInfoGsm) info).getCellSignalStrength();
CellIdentityGsm identityGsm = ((CellInfoGsm) info).getCellIdentity();
list += "cellID: "+ identityGsm.getCid() + "\r\n";
list += "dBm: " + gsm.getDbm() + "\r\n\r\n";
//call whatever you want from gsm / identitydGsm
}
else if (info instanceof CellInfoLte) //if LTE connection
{
list += "Site_"+i + "\r\n";
list += "Registered: " + info.isRegistered() + "\r\n";
CellSignalStrengthLte lte = ((CellInfoLte) info).getCellSignalStrength();
CellIdentityLte identityLte = ((CellInfoLte) info).getCellIdentity();
//call whatever you want from lte / identityLte
}
else if (info instanceof CellInfoWcdma) //if wcdma connection
{
CellSignalStrengthWcdma wcdmaS = ((CellInfoWcdma) info).getCellSignalStrength();
CellIdentityWcdma wcdmaid = ((CellInfoWcdma)info).getCellIdentity();
list += "Site_"+i + "\r\n";
list += "Registered: " + info.isRegistered() + "\r\n";
//call whatever you want from wcdmaS / wcdmaid
}
} catch (Exception ex) {
Log.i("neighboring error 2: " ,ex.getMessage());
}
}
Log.i("Info display", list); //display everything.
And while we're busy, just a heads up, the LTE parsing is all screwy (you will see if you do getCi(), getTac() etc. ), so I wrote my own parsing class, and posted my answer here.
Hede of warning though, when you start to see that your neighboring cell info is totally wrong... (the problem that I'm currently at), this dilemma is also posted here. Good luck, and let me know if this part is not a issue for you
Try this (according to cocorico):
String ssignal = signalStrength.toString();
String[] parts = ssignal.split(" ");
Where signalStrength.toString() comes from signalStrength.
The parts[] array will then contain these elements:
part[0] = "Signalstrength:" _ignore this, it's just the title_
parts[1] = GsmSignalStrength
parts[2] = GsmBitErrorRate
parts[3] = CdmaDbm
parts[4] = CdmaEcio
parts[5] = EvdoDbm
parts[6] = EvdoEcio
parts[7] = EvdoSnr
parts[8] = LteSignalStrength
parts[9] = LteRsrp
parts[10] = LteRsrq
parts[11] = LteRssnr
parts[12] = LteCqi
parts[13] = gsm|lte|cdma
parts[14] = _not really sure what this number is_
So, LTEdBm is :
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
int dbm = 0;
if ( tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE){
// For Lte SignalStrength: dbm = ASU - 140.
dbm = Integer.parseInt(parts[8])-140;
} else {
// For GSM Signal Strength: dbm = (2*ASU)-113.
if (signalStrength.getGsmSignalStrength() != 99) {
int intdbm = -113 + 2
* signalStrength.getGsmSignalStrength();
dbm = Integer.toString(intdbm);
}
}

connection to aspx page from android?

I have developed an application get location but i need to save it to server using aspx webpage.
I have created tables on the webpage and i need to save these lat,long to the webpagepage using the unique id as imei?
I have created a table with imei, latlong, datetime
aspx name /http://Log.aspx/
can anybody help me please I have searched many but I couldn't understand.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
// initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// check if GPS is enabled
// else switch on gps
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
}
else {
// get a location provider from location manager
// empty criteria searches through all providers and returns the
// best one
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("disabled", false);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
}
else {
// get cell id
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
TextView tv1 = (TextView) findViewById(R.id.locationResults);
if (loc != null) {
tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
// to write it to file
appendData("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 15, 0,
this);
}
}
}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
// sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt(((lat - curStatLat) * (lat - curStatLat))
+ ((lon - curStatLon) * (lon - curStatLon)));
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
// to write the file..
appendData(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting gps NETWORK ID : ");
}
}
I wrote a WS few months back like this:
<%# WebService Language="VBScript" Class="DataIns" %>
Imports System
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data
Imports System.Globalization
<WebService(Namespace:="http://www.mysite.org/webservices/")> Public Class DataIns :Inherits WebService
<WebMethod()> Public Function devIns (ByVal dm As String) As String
Dim strArr() As String
Dim rtnVal As String
strArr = dm.split("^")
Dim connection As SqlConnection
Dim connection1 As SqlConnection
Dim connection2 As SqlConnection
Dim cmd As SqlCommand
Dim connectionString As String
connectionString = ConfigurationManager.ConnectionStrings("sqlsds").ConnectionString
connection = New SqlConnection(connectionString)
Dim cmdtrans As SqlCommand
Dim cmdCheck As SqlCommand
Dim result as String
Dim sqltrans as String
Dim notes as String
Dim notes1 As String
sqltrans= "select dbo.fnCheckBlackList(#p_imei)"
cmdtrans=new sqlcommand(sqltrans,connection)
cmdtrans.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection.Open()
notes=cmdtrans.ExecuteScalar()
Catch ex As Exception
notes = ex.Message
Finally
connection.Close()
End Try
notes = If(IsDBNull(notes),"","")
if notes.Trim().Equals("TIMEUP") then
Context.Response.Output.Write("Save Completed Wipeout")
Context.Response.End()
return string.Empty
else
connection1 = New SqlConnection(connectionString)
result = "select dbo.fnCheckImeiDateWise(#p_imei)"
cmdCheck=new sqlcommand(result,connection1)
cmdCheck.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection1.Open()
notes1=cmdCheck.ExecuteScalar()
Catch ex As Exception
notes1 = ex.Message
Finally
connection1.close()
End Try
if notes1.Trim().Equals("FINE") then
connection2 = New SqlConnection(connectionString)
cmd = New SqlCommand("dbo.spInsertDeviceData", connection2)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#p_imei", strArr(0))
cmd.Parameters.AddWithValue("#p_location", strArr(1))
cmd.Parameters.AddWithValue("#p_aic", Integer.Parse(strArr(2)))
cmd.Parameters.AddWithValue("#p_adc", Integer.Parse(strArr(3)))
cmd.Parameters.AddWithValue("#p_ail", strArr(4))
cmd.Parameters.AddWithValue("#p_adl", strArr(5))
cmd.Parameters.AddWithValue("#p_tsss", Double.Parse(strArr(6)))
cmd.Parameters.AddWithValue("#p_ts", Double.Parse(strArr(7)))
cmd.Parameters.AddWithValue("#p_tsgp", Double.Parse(strArr(8)))
cmd.Parameters.AddWithValue("#p_tvpc", Double.Parse(strArr(9)))
Try
connection2.Open()
rtnVal = cmd.ExecuteNonQuery()
Catch ex As Exception
rtnVal = ex.Message
Finally
connection2.Close()
End Try
'Context.Response.Output.Write(rtnVal)
Dim parameterString As String
Dim dow2 As String
parameterString = ConfigurationManager.AppSettings("FREQUENCY")
parameterString = parameterString + "|"
parameterString = parameterString + getNewTime(ConfigurationManager.AppSettings("UPDATEAT1"))
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFWEEK1")
dow2 = ConfigurationManager.AppSettings("DAYOFWEEK2")
if String.IsNullOrEmpty(dow2) then
else
parameterString = parameterString +"*"
parameterString = parameterString + dow2
end if
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFMONTH")
Context.Response.Output.Write("Save Completed" + "|"+ parameterString)
Context.Response.End()
return string.Empty
else
Context.Response.Output.Write("ERROR")
Context.Response.End()
return string.Empty
End If
End If
end function
end class
and this was called like
http://www.mysite.org/DataIns.asmx/dIns?dm=<data-separated=by-^>

How to programmatically create and read WEP/EAP WiFi configurations in Android?

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?

Categories

Resources