Android - checking if the device is connected to the internet - android

is there any simple way, how to check if the device is actively connected into internet (= is connected via GPRS, EDGE, UMTS, HSDPA or Wi-Fi)?
Thanks

Yes, I use isReachable.
public class Extras {
public static class Internet {
public static boolean isOnline() {
try {
InetAddress.getByName("google.ca").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
}
}

I use this in one of my apps:
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null && ni.isConnected());
}
You will need these permissions in your Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

You can try retreaving the Local IP address to check whether device is connected to Internet.
for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); enumeration.hasMoreElements();) {
NetworkInterface networkInterface = enumeration.nextElement();
for (Enumeration<InetAddress> enumIpAddress = networkInterface.getInetAddresses(); enumIpAddress.hasMoreElements();) {
InetAddress iNetAddress = enumIpAddress.nextElement();
if (!iNetAddress.isLoopbackAddress()) {
return iNetAddress.getHostAddress().toString();
}
}
}
The return iNetAddress.getHostAddress().toString(); will give you the IP address. You need to add permission
<uses-permission android:name="android.permission.INTERNET" />
Note: If you are working in Emulator it will retun the emulator IP (generally it will be 10.0.2.15)

Related

Getting Wrong Network Interface in android?

I have update my mobile to Android Lollipop, before updating to Lollipop it works fine. Now I am facing problem with network interface.
if (isWifiConnected()) {
Log.d(TAG,"Wifi is connected");
mNetIf = Utils.getActiveNetworkInterface();
String name = mNetIf.getName();
Log.d(TAG, "network interface in constructor" + NetworkInterface.getByName(name));
//do some multicast Operations.
}
If the WiFi is connected I should do some multicast operation in WiFi.
iswifiConnected method
public boolean isWifiConnected(){
ConnectivityManager connManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
return true;
}
return false;
}
Utils.getActiveNetworkInterface
public static NetworkInterface getActiveNetworkInterface() {
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
return null;
}
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
/* Check if we have a non-local address. If so, this is the active
* interface.
*
* This isn't a perfect heuristic: I have devices which this will
* still detect the wrong interface on, but it will handle the
* common cases of wifi-only and Ethernet-only.
*/
while (inetAddresses.hasMoreElements()) {
InetAddress addr = inetAddresses.nextElement();
if (!(addr.isLoopbackAddress() || addr.isLinkLocalAddress())) {
return iface;
}
}
}
return null;
}
Log
Wifi is connected
network interface in constructor**[rmnet0][3]t** [/fe80::32e3:daf0:ba51:f971%rmnet0%3][/27.57.104.11]//3g network interface
I am wondering how the app got 3g interface. It should get wlan interface, it work in all other mobile. Is it a bug?
Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You are using the ConnectivityManger but, to use the WiFi network in Android, the best choice is to use the WifiManager: it has many features dedicated to Wifi. In particular, if you want to get a NetworkInterface object referencing the WiFi Interface, you can use the following method:
public static NetworkInterface getActiveWifiInterface(Context context) throws SocketException, UnknownHostException {
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
//Return dynamic information about the current Wi-Fi connection, if any is active.
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if(wifiInfo == null) return null;
InetAddress address = intToInet(wifiInfo.getIpAddress());
return NetworkInterface.getByInetAddress(address);
}
public static byte byteOfInt(int value, int which) {
int shift = which * 8;
return (byte)(value >> shift);
}
public static InetAddress intToInet(int value) {
byte[] bytes = new byte[4];
for(int i = 0; i<4; i++) {
bytes[i] = byteOfInt(value, i);
}
try {
return InetAddress.getByAddress(bytes);
} catch (UnknownHostException e) {
// This only happens if the byte array has a bad length
return null;
}
}
I think the problem is that getInetAddresses() returns a list of interfaces, and getActiveNetworkInterface is only returning the first one no matter what.
And so the interface you are getting depends on the order of the list which getInetAddresses() returns.
That being said, one of the solutions could be: look at the up interface, using isUp().
http://developer.android.com/reference/java/net/NetworkInterface.html#isUp()
Android would turn off the cellular connection to save power when connected to wifi networks, so by looking at only the UP interface, you should able to pin point the WiFi interface.

how to check a network is connected to wifi in android [duplicate]

This question already has answers here:
Detect network connection type on Android
(14 answers)
Closed 9 years ago.
Now I am developing an application. I checked the internet connection in android using ConnectivManager. I checked for Mobile 3g and for WIFI.I turn off the WIFI connection and checked it works as what i want. Then I turn on the WIFI connection but disconnected all networks in WIFI. Now I checked but it shows the WIFI is connected but I want to check whether a network is connected to WIFI when WIFI is on or not connected to WIFI when WIFI is on. I do not know how to code it. Can anyone please help with the required code?
Thanks in advance
public boolean isWifiEnabled(){
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
return false;
}
Don't forget to use the following permission
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
To Check if internet is connected via WiFi or mobile
public static boolean hasInternet(Activity a) {
boolean hasConnectedWifi = false;
boolean hasConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) a.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("wifi"))
if (ni.isConnected())
hasConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("mobile"))
if (ni.isConnected())
hasConnectedMobile = true;
}
return hasConnectedWifi || hasConnectedMobile;
}
With this piece of code you should be able to use the ConnectivityManager. From there you can check if it is connected or even available.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
To check network connection
public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}
In your activities
if(Checknetwork.isInternetAvailable(MainActivity.this)
{
// do something
}
Remember to add permission in manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
This also check's if you have connection to mobile network or wifi.

How to check internet access (INCLUDING tethering!) on Android?

I am looking for a piece of code that would check network connectivity, of an Android device, including tethering, not only the wireless channels.
I have spent hours online looking for such a thing, but without any result! All the functions I found out manage only wireless net tests. Nothing with tethering. So is it at least possible? Do you have some corresponding?
this checks if Tethering is enabled. Cut from a class I changed to get adbWireless working over a tethered connection:
// check if tethering is on
try {
Method[] wmMethods = mWifiManager.getClass().getDeclaredMethods();
for(Method method: wmMethods)
if("isWifiApEnabled".equals(method.getName()))
return (Boolean) method.invoke(mWifiManager);
return false;
} catch (Exception x) {return false;}
And you also need android.permission.ACCESS_WIFI_STATE
Check this out:
public static boolean isOnline(Context context) {
boolean isOnline = false;
try {
final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if(activeNetwork != null && activeNetwork.isConnected() && activeNetwork.isAvailable()) {
isOnline = true;
} else {
isOnline = false;
}
} catch(Exception e) {
Log.e(Config.LOG_TAG, e.toString());
isOnline = false;
}
return isOnline;
}
Also add such permission into AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How to detect WiFi tethering state

I want to know how to detect state of WiFi tethering. I've seen an article: Android 2.3 wifi hotspot API But it doesn't work! It returns always WIFI_AP_STATE_DISABLED = 1. It doesn't depend on real state of WiFi tethering.
Using reflection:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Method[] wmMethods = wifi.getClass().getDeclaredMethods();
for (Method method: wmMethods) {
if (method.getName().equals("isWifiApEnabled")) {
try {
boolean isWifiAPenabled = method.invoke(wifi);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
As you can see here
In addition to the reflexion, to get the Wifi tethering status update, you can listen to this broadcast Action :
IntentFilter filter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
To get all tethering option update :
IntentFilter filter = new IntentFilter("android.net.conn.TETHER_STATE_CHANGED");
Those actions are hidden inside the Android source code
First, you need to get WifiManager:
Context context = ...
final WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Then:
public static boolean isSharingWiFi(final WifiManager manager)
{
try
{
final Method method = manager.getClass().getDeclaredMethod("isWifiApEnabled");
method.setAccessible(true); //in the case of visibility change in future APIs
return (Boolean) method.invoke(manager);
}
catch (final Throwable ignored)
{
}
return false;
}
Also you need to request a permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Here is the Xamarin C# version if anyone is looking:
static Method isWifiApEnabledMethod;
public static bool IsWifiApEnabled ()
{
var wifiManager = WifiManager.FromContext (Application.Context);
if (isWifiApEnabledMethod == null)
{
try
{
isWifiApEnabledMethod = wifiManager.Class.GetDeclaredMethod ("isWifiApEnabled");
isWifiApEnabledMethod.Accessible = true; //in the case of visibility change in future APIs
}
catch (NoSuchMethodException e)
{
Debug.WriteLine ("Can't get method by reflection" + e);
}
catch (System.Exception ex)
{
Debug.WriteLine ("Can't get method by reflection" + ex);
}
}
if (isWifiApEnabledMethod != null)
{
try
{
return (bool)isWifiApEnabledMethod.Invoke (wifiManager);
}
catch (System.Exception ex)
{
Debug.WriteLine ("Can't invoke by reflection" + ex);
}
}
return false;
}
(without using reflection since they say google is restricting it)
I'm writting this answer 10 years later. also I don't know if this can be considered a good aproach or not but I first get the Wlan network interface IPs
and if there is no address I assume that it tethering isn't enabled. if there is an address, I check using the connectivity manger whether WI-FI is connected to a network or not. if there is an IP for the Wlan network interface but it isn't connected to a network, I assume tethering is enabled.
you probably would need to add this line to your manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
code to get the ip of an inteface (this only gets the IPv4, you can modify it to get the IPv6 or both if you want)
// method used to retrieve Wlan ip addresses IPv4 of the device.
public static String IpAddresses() throws NoAddressFoundException, SocketException {
Enumeration<NetworkInterface> Nics = NetworkInterface.getNetworkInterfaces();
while (Nics.hasMoreElements()) {
NetworkInterface NIC = Nics.nextElement();
if (NIC.isUp() && !NIC.isLoopback() && NIC.getName().contains("wlan")) {
Enumeration<InetAddress> Addresses = NIC.getInetAddresses();
while (Addresses.hasMoreElements()) {
InetAddress WlanAddress = Addresses.nextElement();
if (WlanAddress instanceof Inet4Address)
return WlanAddress.getHostAddress();
}
}
}
throw new NoAddressFoundException("No suitable wifi address found");
}
then if there is an address i check if wifi is connected by this method:
//method to check if the device is connected to a Wi-Fi network; it doesn't matter if network has access to internet
public static boolean isWifiConnected(Context context) {
ConnectivityManager ConMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo WifiInfo = ConMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return WifiInfo.isConnected();
}
NOTE: the "NoAddressFoundException" is a custom exception in my app if anyone is wondering. it won't exist in your case.
Reflection is a poor way to achieve this.
We can inspect the DhcpInfo to determine if the device is allocating addresses (mobile hotspot) or is being allocated by another DHCP server.
Here is a kotlin function that will determine if a device is a mobile hotspot, it has not been widely tested so YMMV.
fun isMobileHotspot(manager: WifiManager): Boolean {
val info = manager.dhcpInfo
return (
info.ipAddress == 0
&& info.netmask == 0
&& info.gateway == 0
&& info.serverAddress == 16885952) // 192.168.1.1
}

How to write an Android SocketServer to listen on wifi

I've written a thread using java.net.SocketServer to listen on a particular port. It works fine in the android simulator (using port forwarding). I'm planning to connect over wifi to this port when the app is being used. However, the SocketServer documentation says that if you don't supply an InetAddress, the server listens on localhost.
Am I correct that if I do not supply the address, I will not be able to get a connection over wifi? How can I get the InetAddress of the wifi connection to pass to the SocketServer?
When you create a ServerSocket you listen to a port on the localhost. It's up to you if you want to nominate your own local host address.
Read these two articles:
Implement a simple Socket Server in Eclipse
Simple communication using java.net.Socket
Remember to have a WiFi lock and the appropriate permissions.
You can try the following code.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
private String getIPAddress() throws SocketException {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null || !info.isConnected()){
return null;
}
switch (info.getType()) {
case ConnectivityManager.TYPE_WIFI: {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi == null) break;
WifiInfo wifi_info = wifi.getConnectionInfo();
String ipAddress = intToIp(wifi_info.getIpAddress());
return ipAddress;
}
case ConnectivityManager.TYPE_MOBILE: {
Enumeration<NetworkInterface> interfaceEnumerations = NetworkInterface.getNetworkInterfaces();
while(interfaceEnumerations.hasMoreElements()){
NetworkInterface interfac = interfaceEnumerations.nextElement();
Enumeration<InetAddress> inetAddresses = interfac.getInetAddresses();
while(inetAddresses.hasMoreElements()){
InetAddress address = inetAddresses.nextElement();
if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) {
String addressIp = address.getHostAddress();
if(TextUtils.isEmpty(addressIp) || !addressIp.matches("(\\d{1,3}.){3}\\d{1,3}")) continue;
return addressIp;
}
}
}
break;
}
}
return null;
}

Categories

Resources