How to check the internet connection continuously while app is running
java file this will check for internet when app is start running
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class isNetworkAvailable extends Activity {
private ImageButton btn;
private Handler h = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_is_network);
btn = (ImageButton) findViewById(R.id.bu);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restar();
}
});
if (!isNetworkAvailable()) {
//Create an alert dialog
AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(isNetworkAvailable.this);
Checkbuilder.setIcon(R.drawable.error);
Checkbuilder.setTitle("Error!");
Checkbuilder.setMessage("Check Your Internet Connection.");
//Builder Retry Button
Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Restart The Activity
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alert = Checkbuilder.create();
alert.show();
} else {
if (isNetworkAvailable()) {
Thread tr = new Thread() {
public void run() {
try {
sleep(4);
} catch (Exception e) {
e.printStackTrace();
} finally {
Intent i = new Intent(isNetworkAvailable.this, MainActivity.class);
startActivity(i);
finish();
}
}
};
tr.start();
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void restar(){
Intent intenet =new Intent(this,isNetworkAvailable.class);
startActivity(intenet);
finish();
}
}
layout file for above java code
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context=".isNetworkAvailable">
<ImageView
android:id="@+id/imageView2"
android:layout_width="389dp"
android:layout_height="439dp"
android:contentDescription="no internet check your connection"
android:src="@raw/no"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/bu"
android:layout_width="335dp"
android:layout_height="80dp"
android:layout_below="@id/imageView2"
android:layout_marginTop="32dp"
android:contentDescription="Tap to retry"
android:src="@raw/r"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2" />
</android.support.constraint.ConstraintLayout>
and just add this line of code will check internet connection continuously
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/error.html");
and your android mainfest should be like this
<application
android:icon="@mipmap/ic_app"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_app_round"
android:supportsRtl="true"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="@style/Theme.AppCompat.NoActionBar">
<activity
android:name=".isNetworkAvailable"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
place this file under assets with name error.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<title>No Connection</title>
<!-- Stylesheets-->
<style type="text/css">
body{
background: #E1e1e1;
}
#cloud{
width: 300px;
height: 120px;
background: #676767;
background: -webkit-linear-gradient(-90deg,#676767 5%, #676767 100%);
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
position: relative;
margin: 150px auto 0;
opacity: .5;
}
#cloud:before, #cloud:after{
content: '';
position:absolute;
background: #676767;
z-index: -1;
}
#cloud:after{
width: 100px;
height: 100px;
top: -50px;
left:50px;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
}
#cloud:before{
width: 120px;
height: 120px;
top: -70px;
right: 50px;
-webkit-border-radius: 200px;
-moz-border-radius: 200px;
border-radius: 200px;
}
.shadow {
width: 300px;
position: absolute;
bottom: -10px;
background: black;
z-index: -1;
-webkit-box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
-moz-box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
h1{
color: #fff;
font-size: 25px;
padding-top: 1px;
text-align: center ;
margin: 2px auto;
}
h2 {
color: #fff;
font-size: 17px;
padding-top: 15px;
text-align: center;
margin: 5px auto;
}
h4 {
color: #fff;
font-size: 14px;
margin: 0 auto;
padding: 0;
text-align: center;
}
</style>
<body>
<div id="cloud"><h1>Whoops!</h1>
<h2>Slow or No internet Connection :(</h2>
<h4>Please Check your WiFi or Mobile Internet!</h4>
<span class="shadow"></span></div>
</body>
</html>
you need to input all the above code to make it work fine . hope this will help you
Android Check Internet connection continuously
I want to use it in every activity. How can I modify this code?
Create a BaseActivity
class which extends AppCompatActivity
, and then make all of your Activity
classes extend this BaseActivity class. Put your code to check internet connection in the BaseActivity
class. cheers :)
How to keep checking all the time for internet connection in flutter
To check the internet connection you can use the package data_connection_checker
:
bool hasConnection = false;
@override
void initState() {
super.initState();
DataConnectionChecker().onStatusChange.listen((status) {
setState(() {
switch(status){
case DataConnectionStatus.connected:
hasConnection = true;
break;
case DataConnectionStatus.disconnected:
hasConnection = false;
break;
}
});
});
}
I usually go to External Libraries
> data_connection_checker-version
And in the dart file i change the DEFAULT_INTERNAL to 1, for verification to happen every 1 second:
static const Duration DEFAULT_INTERVAL = const Duration(seconds: 1);
How to continuously check internet connect or not on Flutter?
The connectivity package will do what you want. It has an onConnectivityChanged
stream which you can subscribe to. This will notify your app when the connectivity state changes. But just because your device is connected to a network doesn't mean it can access your server and be connected. So a DNS lookup would be a good idea before then updating the internal state of your application.
https://pub.dartlang.org/documentation/connectivity/latest/connectivity/Connectivity-class.html
Check internet connection constantly
There are a few ways of going about this:
- You can store an asset (maybe a
1px x 1px
GIF
image) on your server and constantly keep polling for this (continuous requests everyx
seconds). Of course you wanna make sure this image is not cached. If the request fails, you can assume that the network is not available. This is easy to implement, but is not efficient because polling sends tons of HTTP headers over the wire. - This is much more efficient - implement a
WebSocket
connection in your client and server and open a socket upon opening the app. If the socket drops, you can display theConnectivity Lost
message. This doesn't require sending of HTTP requests repeatedly. This is much more efficient, but more work will be required to implement this.
You can write services for either of these in Ionic.
At it's simplest, option #1 can be:
setInterval(ajaxCall, 3000); //3000 MS == 3 sec
function ajaxCall() {
$.ajax('/testConnectivityUrl').then(function(response) {
console.log("Still connected");
}, function(err) {
console.log("Lost connection");
}
}
I've used jQuery, but you can do this with vanilla JS or Angular or Ionic services or factories.
How to check for internet connection repeatedly?
Best way to check for internet connection works and tested on Swift 2.0
1) Create a new swift file connection.swift and include this code below
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
You can use this method anywhere
if Reachability.isConnectedToNetwork() == true {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
}
If the user is not connected to the internet, you may want to show them an alert dialog to notify them.
if Reachability.isConnectedToNetwork() == true {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
Took idea from
https://github.com/Isuru-Nanayakkara/Reach
Checking for internet connection constantly with android
See this answer: How to check internet access on Android? InetAddress never times out
However I would like to point out something that you may have overlooked: checking for constant internet connectivity will consume power. A lot of power. So, what you may end up doing is draining your user's batteries (which would have a lot of negative consequences, not just poor reviews).
So, maybe we could talk about why you need to check for internet connectivity constantly? You might want to look into how you can buffer up your network requests or caching ,etc. Feel free to edit this question or even create a new one, just link to it :)
Related Topics
How to Change Cell Background Color in Wpf Datagrid
Select Multiple Fields from List in Linq
How to Redirect to Login Page If Session Is Not Available in MVC
How to Save Mailmessage Object to Disk as *.Eml or *.Msg File
How to Create a 2D Array from a CSV File
How to Use Decimal Type in Mongodb
How to Disable Cursor in Textbox
Sorting a Collection Containing Strings And/Or Numbers
Asp.Net Core Get Json Array Using Iconfiguration
How to Check If Multiple Values in an Array Are Equal to One String
Calculate a Checksum for a String
C# Foreach (Property in Object)... Is There a Simple Way of Doing This
How to Determine Browser Window Size on Server Side C#
Selenium.Webdriver.Chromedriver Slow to Launch - Why