check internet activity - android

I done an app that uses a webview to listen audio from internet. Now, I add a method (isOnline) to check if there's (or not) an internet activity. I've a doubt: I can use this method running always in OnCreate?
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;

If you block the execution of the onCreate() aka the UI thread will be blocked and your app will throw ANR (Application Not Responding) exception.
However your method doesn't tell you that you are connected to the interned, it just tell you that your device isConnectedOrConnecting to nearest router. What is after that you don't know.
For check real internet connection you need to make a request to a server, such as www.google.com and if you get the answer then you have the connection live.
And another thing, you don't need to monitor your connection continuously. In the most simple manner you can do this in a background thread from time to time, but only if you cannot get events from your radio player.

Related

How to check the connection status in Android avoiding StrictMode

I created a function that returns a boolean based on the presence of an internet connection, this function it is called different times from different java classes.
The only way that I find to use it is to use the StrictMode.setThreadPolicy (i know that it's not a good practice).
How I can solve my problem ?
public boolean checkConnection() {
boolean response = false;
try {
//StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
URL url = new URL(databaseManagement.getSettingValue("urlCheckConnection", context));
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
response = httpURLConnection.getResponseCode() == 200;
httpURLConnection.disconnect();
httpURLConnection.getInputStream().close();
}
}
} catch (Exception e) {
response = false;
wil.WriteFile("checkConnection - Exception: " + e.getMessage(), context);
}
return response;
}
It is possible that this method will block the calling thread for up to 3 seconds. Generally speaking you should not do network or file I/O on the main (UI) thread because that can cause the app to appear non-responsive (and Android will generate an ANR exception in that case). There are various alternatives you could use, depending on your situation. Here are two:
Don't ever call this method on the main (UI) thread. Always perform your Internet connectivity checks on background threads
Make the method asynchronous and provide a callback interface. The caller would then call the method (which will return immediately after launching the connectivity check on a background thread) and then the callback would be triggered when the connectivity check is completed. If this must be done on the main (UI) thread, you should show a progress dialog or similar while you are executing the connectivity check so that the user doesn't think the app is stuck.
Your question is a bit unclear.
Here is how internet connection is checked in my app:
private fun isConnected(): Boolean {
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo: NetworkInfo? = connMgr.activeNetworkInfo
return networkInfo?.isConnected == true
}
It still should be tested on the latest Android APIs as there are known changes, e.g. lack of options to emulate network on\off programmatically from tests since some specific version of Android API.
On another hand StrictMode is used to force you and all the rest software developers to write correct programs. Your code which operates with network and data storages should not be executed in the main thread (which is done by default), it should be run in the separate thread. StrictMode tracks this and notify you about violation of this practice either by warning message in logs or by crashing your app (I prefer second one as it is more obvious).
However sometimes you depend on 3rd party library which violates this good practices and keeping yourStrictMode enabled prevents you from using this library.
In any cases StrictMode is usually enabled only for development stage like this:
if (BuildConfig.DEBUG) {
// TODO enable StrictMode policies
}

How to check if internet is not present or slow while scrolling?

I am using Glide library to fetch images from an API. In the case of network connectivity issues, my present implementation just shows the error image. I want to display a toast message if the internet is not present.
About using services: I think it would be an overkill for a simple app to continuously check the internet. Also if images are already on the screen I don't want to raise any alarm. It is only when images are fetched, the notifications should be raised.
I tried to look into Glide's working but was unable to find a good solution.
Precisely, I want to set timeouts for Glide to fetch images. If it fails to do so a toast would be raised to inform user about low internet connectivity. Please suggest how to do so or if there is any other better way to do this.
public static boolean isNetConnected(Context context) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}

Background IntentService Force Closes because device is connected to WiFi but is not authenticated

I am currently using a background IntentService in my Android App to connect to my server to fetch some data and update the App only if connection is available. If the device is connected to mobile network data or a authenticated wifi connection or open wifi connection it works perfectly.
The problem occurs when the device does not have access to Mobile Data Network and is connected to a Wifi source that requires authentication and the connection is not authenticated yet, the service force closes since it is unable to transfer any data through the unauthenticated connection.
My check to the entry point to connect to the server and do the background task is the check below.
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if((conMgr.getActiveNetworkInfo() != null &&
conMgr.getActiveNetworkInfo().isAvailable() &&
conMgr.getActiveNetworkInfo().isConnected()) || WifiConnected() == true){
//do background processing
}
The WifiConnected() method looks like this below.
private boolean WifiConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
SupplicantState supState;
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
return (networkInfo != null && networkInfo.isConnected() && supState.toString().contentEquals("COMPLETED"));
}
So basically what I am checking before doing the background task is whether the device has active network connectivity and is connected or if the connection is wifi, if that connection is authentication complete so that data transfer is possible.
This doesn't seem to work and fails too making the service still force close.
What is the right way to do this check for network connectivity when wifi authentication is involved and then do the background processing?
Thanks.
A good example of this problem is when you are in any starbucks nationwide your android device will automatically connect to attwifi and the wifi status changes to connected because i check isConnected returns true but you will notice that the attwifi at starbucks will not let you transfer any data until you pseudo sign in by navigating to a browser page and accepting their terms of usage and agreement
Method conMgr.getActiveNetworkInfo() calls into ConnectivityService and the result of this call can be null. In the statement (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) you call three times. I suspect there can be NPE here, as one of these calls can return null if network changes from 3g to WiFi at that time. What if you get NetworkInfo instance first, and them call isAvailable() and isConnected() on it (similar to how you did it in WifiConnected())?
You could move the connectivity check in your activity (or wherever else you have the context) and start the service from there.
Thus you won't have the force close constraint of the intentService and it should work fine.
Edit:
Ok got it! Here's what you can do to be sure that the user has access to Internet:
private boolean hasInternetAccess() {
boolean hasInternetAccess = false;
try {
//I set google but you can try anything "reliable"...
//isReachable(1) the timeout in seconds
hasInternetAccess = InetAddress.getByName("www.google.com").isReachable(1);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hasInternetAccess;
}
So your check becomes:
If(WifiConnected() && hasInternetAccess()){
//Do background Work...
}
This is does some sort of ping to ensure the user has internet.
Don't forget that this method needs to be executed in a separate thread or it'll throw a NetworkOnMainthreadException. Here you're safe since you are in an IntentService that has its own thread. But I precise for the ones that might see this thread. By the way I suggest you to change the title of the this thread since the actual problem is not really related to the service but the access to internet.
Here's the reference: Test Internet Connection Android
I hope this helps.
or you can write a receiver for Connectivity change. It would be the best in your case.
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

Checking for network availability not working

I use the following code to check the network status of an android device (Source)
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
After running it on my phone, I find that it does return "true" when network is available. But when I turn on the Airplane Mode on my phone, I find that it still returns "true". What is wrong here? Also, does a "true" mean that the wifi is also on or just that cellular network is available?
Thanks
PS: And yes, I have added the ACCESS_NETWORK_STATE permission in the manifest.
You are right. True value means that there is internet connection from wifi or cellular network. You can have air plane mode on but if you still have wifi on your method will return true.
See also: http://developer.android.com/reference/android/net/NetworkInfo.html#isConnected()

connectivitymanager.getActiveNetworkInfo() returning true when Internet is off (Android)?

This is the code I am using to determine if the phone is connected to the Internet:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
On an emulator, this is returning true even when I turn my computer's Wi-Fi off. I see a 3G sign on the topmost bar of the emulator, even when the computer is off the Internet. Is there something wrong with my code, or is this an emulator problem?
You should call isConnected instead of isConnectedOrConnecting if you want to determine whether the device is connected at the time of call to isOnline.
Generally, there are many problems/bugs with hardware-features APIs on the emulator, this might be one of them. Your code is fine.

Categories

Resources