I want to add in my app boolean to check if device is connected to Internet or not.
I found this question
But I can't get it to work in my app.
This is the code:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
}
} else {
}
return false;
}
It's in my MainActivity. I get this error:
The method isNetworkAvailable() in the type MainActivity is not
applicable for the arguments (Context)
Why am I getting this error? What's wrong with my code? or I just need to put those methods in separate activities?
make sure that you are adding particular permission in androidmanifest.xml then
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
replace with this code
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
}
} else {
}
return false;
}
your isNetworkAvailable, takes not parameter but your invoking it with a context object
if (isNetworkAvailable(context))
causing the compile time error. You can change the signature of isNetworkAbailable like
private static boolean isNetworkAvailable(Context context) {
}
Related
I am creating an android app which relies on the internet. How do I handle the case in which the phone is connected to the Wifi but it is not actually working?
As in the case when there is an exclamation mark next to the wifi icon in the StatusBar?
Add Permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Try this mehod :
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return new Boolean(true);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
You can detect wifi speed and if the speed is very low then you can handle the situation.
First, check if your connection type is wifi-
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
if(isWifi){
WifiInfo wifiInfo = wifiManger.getConnectionInfo();
int mbps = wifiInfo.getLinkSpeed();
}
I found a lot of answer about this but unable to implement those also.
I want to implement this code here but not able to do so.
This code I found on google documentation.
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#DetermineConnection
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
}
StringBuilder sb = new StringBuilder();
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
if (is != null) {
is.close();
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
UPDATE:
Update the solution for internet checking. What works for me now is this
fun isNetworkAvailable(context: Context?): Boolean {
if (context == null) return false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
return capabilities != null &&
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
} else {
try {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
} catch (ignored: Exception) {
}
}
return false
}
OLD:
Simple function to check the internet connection
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
return false;
}
}
and in your AndroidManifest.xml you should add the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
protected boolean isNetworkAvilable() {
boolean isNetworkAvilable = false;
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable() && info.isConnected()) {
isNetworkAvilable = true;
}
return isNetworkAvilable;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
}
return false;
}
like this you can make this method in your common file for your project
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
and use like
if(commonfile.isNetworkAvilable(pass your context here))
{
//call your method
}
and don't forgot to add permission for Internet in your manifeast
what happens if your device connected to internet, but no input data? You also have to check whether you are receiving data or not. Check below code to see you are connected internet and able access data. You just need to ping a site and see if your responce back is 200.
public class internetchek extends AsyncTask<Void,Void,Void> {
public boolean connection;
Context ctx;
public internetchek(Context context){
this.ctx = context;
}
public internetchek(){
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
if(isNetworkAvailable(this.ctx))
{
Log.d("NetworkAvailable","TRUE");
if(connectGoogle())
{
Log.d("GooglePing","TRUE");
connection=true;
}
else
{
Log.d("GooglePing","FALSE");
connection=false;
}
}
else {
connection=false;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
public static boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.d("GooglePing","IOEXCEPTION");
e.printStackTrace();
return false;
}
}
UPDATE: If you want to use it for other classes you can do this..make sure you put below code in AsyncTask or background running thread.
if(internetchek.isNetworkAvailable(this.ctx)||internetchek.connectGoogle())
{
//Do your stuff here. when you have internet access
}
i used this code to call web service from xamarin :
void OnWebserviceRetrievedInformation1 (object sender, EventArgs e)
{
MyService.MonoDataService ms = new MyService.MonoDataService ();
ms.Url = "http://10.0.2.2:11339/MonoDataService.asmx";
TextView tx=FindViewById<TextView> (Resource.Id.textView1);
tx.Text = ms.Hello ("Hadi");
}
but when web server is offline my apps is in loop !
how can check web service is available and then call ?
Try something like this :
public bool IsConnected()
{
try{
var cm = (ConnectivityManager)GetSystemService (Context.ConnectivityService);
var netInfo = cm.ActiveNetworkInfo;
if (netInfo != null && netInfo.IsConnected)
{
//Network is available but check if we can get access from the network.
var url = new URL("http://www.Google.com/");
var urlc = (HttpURLConnection) url.OpenConnection();
urlc.SetRequestProperty("Connection", "close");
urlc.ConnectTimeout = 2000; // Timeout 2 seconds.
urlc.Connect();
if (urlc.ResponseCode == 200) //Successful response.
return true;
else {
Log.Debug ("No Internet", "No internet connection.");
return false;
}
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine (ex.Message);
}
return false;
}
Check Using this method:
public boolean isConnected()
{
try{
ConnectivityManager cm = (ConnectivityManager) getSystemService
(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
//Network is available but check if we can get access from the network.
URL url = new URL("http://10.0.2.2:11339/MonoDataService.asmx"");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // Timeout 2 seconds.
urlc.connect();
if (urlc.getResponseCode() == 200) //Successful response.
{
return true;
}
else
{
Log.d("NO INTERNET", "NO INTERNET");
return false;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
this is my class that checks if the device is connected to the internet.
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(
"http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000);
urlc.setReadTimeout(4000);
urlc.connect();
// networkcode2 = urlc.getResponseCode();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return (false);
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
then i call it here but it doesnt seem to return true or false. there are no errors and my app doesnt crash it just doesnt print anything out. anyone know why?
public void CheckInternet(){
// Boolean isInternetPresent;
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// isInternetPresent = cd.isConnectingToInternet();
if (cd.isConnectingToInternet()) {
// Internet Connection is Present
Log.i(TAG, "INTERNET IS GUUD");
} else {
// Internet connection is not present
// Ask user to connect to Internet
Log.i(TAG, "INTERNET IS NOOOO GUUD");
}
}
Create a class :
public class Utility {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Then you call methode from activity, it will return true or false:
Utility.isNetworkAvailable(AnyActivity.this);
And don't forget to add permission to android manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
This isn't the correct approach to checking for internet connectivity. You should be using Android's built in ConnectivityManager class for this.
It's quite simple to use, you can simply do the following to check for network connectivity:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
This will also allow you to determine things like the type of connection, if it's monitored, etc. so that you can make informed decisions about the network tasks you are executing.
There is more info in this lesson on the Android Developers site.
You must do it in an asynctask. I use http://clients3.google.com/generate_204
to detect connection.
import java.net.HttpURLConnection;
import java.net.URL;
...
private int inter = 0;
...
new checkconne().execute();
...
class checkconne extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
int kk=0;
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
kk= urlc.getResponseCode();
} catch (IOException e) {
Log.e("qweqwe", "Error checking internet connection", e);
}
inter=kk;
return null;
}
#Override
protected void onPostExecute(String file_url) {
if (inter == 204){
Toast.makeText(MainActivity3.this, "is connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity3.this, "No connection", Toast.LENGTH_LONG).show();
}
}
}
call this function :
public static boolean isNetworkAvailable()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 1500;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try
{
httpClient.execute(httpGet);
return true;
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return false;
}
I'm trying to find the way to know when an user has Internet connection, since now I've got this method :
public boolean isNetworkOnline() {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(1);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;
}
This method returns true if user is CONNECTED but not if user has INTERNET CONNECTION, so I thought to if this method returns true, call another method to check if the user has connection to internet. For example someone can be connected to a router but without internet connection so I want to know when the user has internet connection or not.
I've read this answer and this other but all of them is returning me false when I've got Internet connection.... I thought that make a method that makes a ping to www.google.com it's a good approach to know if someone has internet connection so I tried to get this way but it didn't work for me...
Any idea or good approach (if it's better than my thoughts is better) to know when the user has internet connection?
The Simple Way To Check Internet Connectivity
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
Process p1 = Runtime.getRuntime().exec(
"ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal == 0);
if (reachable) {
System.out.println("Internet access");
return reachable;
} else {
return false;
}
} catch (Exception e) {
return false;
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
How To Call it
if (isConnectingToInternet()) {
// internet is connected and work properly...
}
else {
// something went wrong internet not working properly...
}
So simply copy and past the above two methods where you want to check the Internet connectivity. After that check the condition if (isConnectingToInternet()) { }
Can you try this method?
public boolean checkInternectConnection() {
try {
InetAddress inAddress= InetAddress.getByName("http://google.com");
if (inAddress.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
Please check this answer out and see if its helpful or not
You can try out this code
try {
URL url = new URL("http://"+params[0]);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Main.Log("getResponseCode == 200");
return new Boolean(true);
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this is how i fixed this and i use it as a Utility method which can be called from any activity/fragment etc...:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}//check if Wifi or Mobile data is enabled
private static class NetworkAsync extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
HttpURLConnection urlConnection = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlConnection.setRequestProperty("User-Agent", "Android");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(1500);
urlConnection.connect();
return (urlConnection.getResponseCode() == 204 &&
urlConnection.getContentLength() == 0);
} catch (IOException e) {
// Error checking internet connection
}
return false;
}
}//network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException
and now you simply need to call this method from anywhere you want:
public static boolean checkInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
//used execute().get(); so that it gets awaited and returns the result
//after i receive a response
return new NetworkAsync().execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}