This question already has answers here:
Detect network connection type on Android
(14 answers)
Closed 7 years ago.
I am using the following code for checking if internet connection available or not , this code works well if wifi or data disabled from mobile but problem is that this code hangs mobile when data is not receive during internet connected....
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
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;
}
}
<!--Constants.INTERNET_CONNECTION_URL="YOUR_WEB_SERVICE_URL/URL OF GOOGLE";-->
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.vgheater.util.Constants;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class CheckConnectivity {
private Context _context;
public CheckConnectivity(Context context) {
this._context = context;
}
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;
}
public boolean hasActiveInternetConnection() {
if (isConnectingToInternet()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(Constants.INTERNET_CONNECTION_URL).openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(5000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return false;
}
} else {
return false;
}
}
}
You can use it as follows..
private class InternetTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog internetDialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
internetDialog = new ProgressDialog(RegisterUser.this);
internetDialog.setCancelable(false);
internetDialog.setCanceledOnTouchOutside(false);
internetDialog.setMessage(Html.fromHtml("<font color='#616161'>Checking Internet Connectivity.</font>"));
internetDialog.show();
}
protected Boolean doInBackground(String... urls) {
boolean response = false;
try {
response = checkConnectivity.hasActiveInternetConnection();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(Boolean result) {
internetDialog.dismiss();
if (result) {
//do stuff
} else {
new ShowToast(RegisterUser.this, "Connect to Internet & Try Again !!");
}
}
}
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 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 got an error when i just open my app.. on the first screen it show splash activity ... and there's an error
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
and this one the code on my splash activity, dunno on what section it got warn..
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.xxx.xx.helper.SessionManager;
import com.xxx.xx.util.ConnectionDetector;
public class Splash extends AppCompatActivity {
private ConnectionDetector cd;
Boolean isInternetPresent = false;
protected SessionManager session;
AlertDialogManager alert = new AlertDialogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
session = new SessionManager(getApplicationContext());
cd = new ConnectionDetector(getApplicationContext());
Thread timer = new Thread(){
public void run(){
try {
sleep(2000);
} catch (Exception e) {
e.printStackTrace();
} finally {
checking();
}
}
};
timer.start();
}
public void checking() {
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent) {
session.checkLogin();
finish();
} else {
alert.showAlertDialog(Splash.this, "No Connection", "Check Your Internet Connection.",false);
finish();
}
}
}
and this one my connection manager code ..
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
}
I have this Class to check if Internet is accessible:
public class NetworkAvailability extends AsyncTask<Context, Boolean, Boolean> {
Context mContext;
private static boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) ListViewActivity.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting()) {
Log.i("Netzwerkstatus: ", "Netzwerk-Verbindung verfügbar");
return true;
}
return false;
}
public NetworkAvailability(Context mContext) {
this.mContext = mContext;
}
public NetworkAvailability() {
}
#Override
protected Boolean doInBackground(Context... params) {
if (isNetworkAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.de").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
try {
urlc.connect();
} catch (IOException e) {
e.printStackTrace();
}
//i ist 200 bei Internetverbindung
int i = urlc.getResponseCode();
return (i == 200);
} catch (IOException e) {
Log.e("IsInternetAccessible: ", "Konnte Internetverbindung nicht prüfen");
}
} else {
Log.d("IsInternetAccessible:", "Internet nicht verfügbar");
}
return false;
}
Now i want to check if internet is accessible BEFORE parsing a xml.
Here is the snippet where i want to use this class.
if (networkAvailability.execute()) {
XMLParser parser = new XMLParser();
String xml = parser.getXMLFromUrl("http://XXXXXX.de/XX.xml");
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_SYSTEM);
for (int i = 0; i < nl.getLength(); i++) {
// Neue HashMap erstellen
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// Jedes Kind-Knoten zur HashMap
map.put(KEY_UUID, parser.getValue(e, KEY_UUID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_JOBTITLE, parser.getValue(e, KEY_JOBTITLE));
map.put(KEY_JOBINFO, parser.getValue(e, KEY_JOBINFO));
map.put(KEY_IMAGE, parser.getValue(e, KEY_IMAGE));
//Hashmap zur ArrayList hinzufügen
menuItems.add(map);
}
} else {
Log.i("doInBackground:", "Keine Internet-Verbindung");
return null;
}
how can i use the result of my NetworkAvailability class in my if loop as condition?
what you can do is to create a seperate class to check internet connection and then create object of that class and the call the function this will also clean your code.
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
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 then create object for that ConnectionDetector in your activity globaly like
ConnectionDetector cd=new ConnectionDetector(this);
and then where ever you want to use that function just call
if(cd.isConnectingToInternet()){
//internet available
}else{
//internet not available
}
I develope a simple chat app with login and register.
For the communication I use TCP Client and a TCP Server.
If user click to login I connect to the server.
Now I need to check if connected or not. If returns true I start a new intent.
I don't have rooted android phone to see the logs and my computer is to low for the emulator, but maybe the fail can you see in the source.
If the progress dialog done loaded is the app crash. Maybe I need a Exception..
Login:
public void LoginUser() {
class AttemptLogin extends AsyncTask<String, Void, Boolean> {
ProgressDialog pDialog;
private Context context;
public AttemptLogin(Activity activity) {
context = activity;
pDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage(context.getString(R.string.login) + "...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
session = new Session(getBaseContext(), "Azcaq", "Azcaq $$", "Test");
session.client = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
public void messageReceived(String message) {
}
});
session.client.run();
Login();
return null;
}
protected void onPostExecute(final Boolean success) {
pDialog.dismiss();
}
}
new AttemptLogin(this).execute();
}
public void Login() {
if(session.client.isConnected()) {
session.setLogin(true);
Intent intent = new Intent(this, ChatsActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), getString(R.string.connectionfail), Toast.LENGTH_LONG).show();
}
}
TcpClient
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
public class TcpClient {
public static final String SERVER_IP = "82.168.0.198";
public static final int SERVER_PORT = 64000;
private String mServerMessage;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter mBufferOut;
private BufferedReader mBufferIn;
private Boolean connected = false;
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
public Boolean isConnected() {
if(connected) {
return true;
}
return false;
}
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
connected = false;
}
public void run() {
mRun = true;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(socket.isConnected()) {
connected = true;
}
while (mRun) {
try {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
mMessageListener.messageReceived(mServerMessage);
}
} catch (SocketTimeoutException e) {
} catch (IOException e) {
}
}
} catch (SocketException e) {
} catch (Exception e) { } finally {
socket.close();
}
} catch (Exception e) {
}
}
public interface OnMessageReceived {
public void messageReceived(String message);
}
}