After trying and searching on stackoverflow for ways to solve internet connection error on android, I found nothing what works for me. I tryed the code you can see at the bottom but it wont works for internet connection error. mWebView.loadUrl("file:///android_asset/myerrorpage.html"); become executed every time when the url in the browser isnt http://192./loc/index.php. When I have a redirecting at index.php the error file become showed. How can I change that, or know anyone a code that check the internet connection availability and then do something?
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
mWebView.loadUrl("file:///android_asset/myerrorpage.html");
} else {
return true;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_localy);
mWebView = (WebView) findViewById(R.id.webview);
// Brower niceties -- pinch / zoom, follow links in place
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setWebViewClient(new GeoWebViewClient());
// Below required for geolocation
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.setWebChromeClient(new GeoWebChromeClient());
// Load google.com
mWebView.loadUrl("http://192./loc/index.php");
}
}
} catch (Exception e) {
return false;
}
}
Your question isn't very clear.
If you need check connection you need:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
Then if need check for real internet connection you can try something like this:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
And add the ACCESS_NETWORK_STATE permission to the manifest.
Related
Trying to build / test an android WebView app with online & offline features.
But it always load offline page even when internet connection is available.
MainActivity.java:
package com.trial_test.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import java.net.InetAddress;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
if (isNetworkConnected()) {
boolean is_test = isInternetAvailable();
if (isInternetAvailable()) {
// REMOTE RESOURCE
mWebView.loadUrl("https://example.com");
} else {
// LOCAL RESOURCE
mWebView.loadUrl("file:///android_asset/index.html");
}
} else {
// LOCAL RESOURCE
mWebView.loadUrl("file:///android_asset/index.html");
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
}
Trying to build / test an android WebView app with online & offline features.
But it always load offline page even when internet connection is available.
Trying to build / test an android WebView app with online & offline features.
But it always load offline page even when internet connection is available.
files
This was not enough to check internet connection,
You may try this
public class NetworkState {
public Boolean isNetworkAvailable(Context context) {
if (context == null)
return false;
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
return true;
}
}
} else {
try {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
// Log.i("update_statut", "Network is available : true")
return true;
}
} catch ( Exception e) {
}
}
Log.e("update_statut", "Network is available : FALSE ");
return false;
}
}
Then Check your connection
NetworkState networkState =new NetworkState();
if (networkState.isNetworkAvailable(this)) {
//You are online
}else{
//You are offline
}
I want to be able to get a user internet connection. I have tried
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
But this only gets mobile data and wifi connection status, if the user has an expired data plan or doesn't even have any data plan I will not be able to know.
I want to know the internet status before making a server call instead of making a server and running in a runout time error.
Please help I have checked stack overflow, but I keep getting the same answer.
check internet coonnection with this function:
Boolean hasInternet(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network activeNetwork = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
if (capabilities != null) {
if (capabilities.hasCapability(NetworkCapabilities.TRANSPORT_WIFI)) return true;
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return true;
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) return true;
else return false;
}
} else {
try {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
} catch (NullPointerException e){
return false;
}
}
return false;
}
I need a service in the background that constantly pings google. But I have no idea how to do it. I am new here. My method does not work does not repeat. It only works once and it always returns "false" .
isConnectedToServer function
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}}
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isConnectedToServer("http://www.google.com",3000)){
Toast.makeText(this, "Okay", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Not Okay", Toast.LENGTH_SHORT).show();
}}
Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
I see Not Okay once on the screen. Only once. Even when I have an internet connection. What can I do about it?
try this create a class that extends AsyncTask
public class CheckInternet extends AsyncTask<Void, Void, Boolean>{
private static final String TAG = "CheckInternet";
private Context context;
public CheckInternet(Context context) {
this.context = context;
}
#Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "doInBackground: ");
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
if ( executeCommand()) return true;
}
return false;
}
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c "+"www.google.com");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
I have read this Answer About Getting Internet Connection Status in Android:
https://stackoverflow.com/a/22256277/4225644
But It doesn't work properly, for example if i have a network connection with no internet Access, this method takes too long time to return False:
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
How Can I decrease this Time to have a faster answer?
Use this code :
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null)
return false;
else {
if (ni.isConnected())
if (isOnline(context))
return true;
else
return false;
return false;
}
}
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.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(2000);
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 could check if there's connectivity with
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
That's for sure a faster way to determine if there's network acces instead of performing a request and waiting for a failure.
See docs as well.
this code may be help you if you want to check internet is present or not
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
and give permission in your manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I have to develop one android application.
Here i have to develop one twitter integration android application.
i have using below code:
public void onClickTwitt() {
if (isNetworkAvailable()) {
Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key);
twitt.shareToTwitter(_Title);
} else {
showToast("No Network Connection Available !!!");
}
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
Here am getting below error :
The method getSystemService(String) is undefined for the type
SubCate
Please help me...How can i resolve these error ????
public void onClickTwitt() {
if (isNetworkAvailable(this)) {
Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key);
twitt.shareToTwitter(_Title);
} else {
showToast("No Network Connection Available !!!");
}
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
for (NetworkInfo networkInfo : info) {
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
public static boolean isNetworkAvailable(Context context) {
if(context == null) { return false; }
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// if no network is available networkInfo will be null, otherwise check if we are connected
try {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
return true;
}
} catch (Exception e) {
AppLog.e(TAG, "isNetworkAvailable()" , e.getMessage());
}
return false;
}
and then do this
if(isNetworkAvailable(TempOrderActivity.this)) {
//do something
} else {
//do something
}
I use this Code and working great, Copied from my App. Hope this will solve your problem
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}