Get the Network Connection Name — Android App Development
Retrieve the name of the current network connection in Android, and call it from JavaScript in a PhoneGap app.
Someone asked this question on my website. You can use the code below to retrieve the name of the current network connection.
public class NativeAccess {
private WebView mAppView;
private DroidGap mGap;
public NativeAccess(DroidGap gap, WebView view) {
mAppView = view;
mGap = gap;
}
public function getConnectionName() {
String networkProvider = "";
try {
ConnectivityManager cm = (ConnectivityManager) this.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni.isConnected()) {
if (ni.getTypeName() == "mobile") {
networkProvider = ni.getExtraInfo();
} else if (ni.getTypeName() == "WIFI") {
WifiManager wifiManager = (WifiManager) this.getContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
networkProvider = connectionInfo.getSSID();
Log.d("TAG_NETWORK", connectionInfo.getSSID());
}
}
Log.d("TAG_NETWORK", ni.getExtraInfo());
Log.d("TAG_NETWORK", ni.getReason());
}
} catch (Exception e) {
Log.d("TAG_NETWORK", e.getMessage());
}
return networkProvider;
}
}
If you want to call this function from an HTML page, expose the class to JavaScript as shown below, then call the function from JavaScript. This is useful in PhoneGap.
// Add this in onCrete function of the class which extends DroidGap
NativeAccess cna = new NativeAccess(this, appView );
appView.addJavascriptInterface(cna, "NativeAccess");
You can then call the function from JavaScript as follows. Note that the object name must match the name you passed to addJavascriptInterface, so with the code above it would be window.NativeAccess:
var connectionName = window.CustomNativeAccess.getConnectionName() ;