How to Check the Internet Connection Periodically in Whole Application

How to check the Internet Connection periodically in whole application?

You should make an BroadcastReceiver that will be triggered when the connectivity status has changed :

     public class BroadCastSampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

if(currentNetworkInfo.isConnected()){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
}
}
};
}

and then in your AndroidManifest you can check if you have connectivity:

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Download source code - here

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 automatically

You can use a utility class and BroadcastReceiver for this purpose. Below link shows show step by step procedure

http://viralpatel.net/blogs/android-internet-connection-status-network-change/

Checking internet connection in every activity?

public class CheckNetwork {

private static final String TAG = CheckNetwork.class.getSimpleName();

public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}

}
}
}

To check Netowrk

In your activity

  if(CheckNetwork.isInternetAvailable(MainActivtiy.this))  //if connection available
{

}

Everytime you want to check internet pass the activity context returns true if available else false.

Detect whether there is an Internet connection available on Android.

How to check internet access on Android? InetAddress never times out.

How do you check internet ACCESS continously in flutter.dart, not connection

Here is the way you can build Network Aware applications

High level overview

  1. Create a service that listen to Connectivity change events, for

    example wifi, mobile and none (offline). This service will emit

    NewtorkStatus (our custom class) into a stream every time the

    Connectivity changes.

  2. Create consumer for the above NetworkStatus stream that will be

    notified everytime the NetworkStatus changes.

  3. Based on the network status rebuild the HomeScreen to show either

    online or offline contents.

Sounds tricky but its actually easy to implement, we will be using connectivity & provider package to our rescue.

Firstly configure our project to use above dependencies, edit pubspec.yaml to include the dependencies -

dependencies:
flutter:
sdk: flutter
connectivity: ^3.0.6
provider: ^6.0.1

Run $ pub get you synchronise all the dependencies.

Now we will create our own NewtorkStatusService this service will use NetworkStatus enumeration with two states Online & Offline to notify the Connectivity state.

network_status_service.dart

enum NetworkStatus { 
Online,
Offline
}

Now our NetworkStatusService will use the Connectivity package to get status of current connection status (wifi, mobile, none) and based on that it will emit a new NetworkStatus to stream. Our final NetworkStatusService would look something like this -

network_status_service.dart

import 'dart:async';
import 'package:connectivity/connectivity.dart';

enum NetworkStatus { Online, Offline }

class NetworkStatusService {
StreamController<NetworkStatus> networkStatusController =
StreamController<NetworkStatus>();

NetworkStatusService() {
Connectivity().onConnectivityChanged.listen((status){
networkStatusController.add(_getNetworkStatus(status));
});
}

NetworkStatus _getNetworkStatus(ConnectivityResult status) {
return status == ConnectivityResult.mobile || status == ConnectivityResult.wifi ? NetworkStatus.Online : NetworkStatus.Offline;
}
}

Now we will create our won custom widget that will return either an onlineChild or offlineChild based on NetworkStatus value. Here we will use provider package to get NetworkStatus. I would look something like this -

network_aware_widget.dart

import 'package:flutter/material.dart';
import 'package:flutter_network_aware_app/services/network_status_service.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class NetworkAwareWidget extends StatelessWidget {
final Widget onlineChild;
final Widget offlineChild;

const NetworkAwareWidget({Key? key, required this.onlineChild, required this.offlineChild})
: super(key: key);

@override
Widget build(BuildContext context) {
NetworkStatus networkStatus = Provider.of<NetworkStatus>(context);
if (networkStatus == NetworkStatus.Online) {
return onlineChild;
} else {
_showToastMessage("Offline");
return offlineChild;
}
}

void _showToastMessage(String message){
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1
);
}
}

Here I am also using the FlutterToast to show toast message (just to add some interactivity to app)

Now's the fun part we will bring all the pieces together to make our app respond to NetworkStatus value. We will use out custom made widget inside a StreamProvider widget. The StreamProvider will subscribe on the NewtorkStatusService networkStatusController stream and trigger a build on child components every time the NetworkStatus changes to Online or Offline. Here's how it will look -

home.dart

import 'package:flutter/material.dart';
import 'package:flutter_network_aware_app/services/network_status_service.dart';
import 'package:flutter_network_aware_app/ui/components/network_aware_widget.dart';
import 'package:provider/provider.dart';

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Network Aware App"),
),
body: StreamProvider<NetworkStatus>(
create: (context) =>
NetworkStatusService().networkStatusController.stream,
child: NetworkAwareWidget(
onlineChild: Container(
child: Center(
child: Text(
"I am online",
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.w600),
),
),
),
offlineChild: Container(
child: Center(
child: Text(
"No internet connection!",
style: TextStyle(
color: Colors.grey[400],
fontWeight: FontWeight.w600,
fontSize: 20.0),
),
),
),
),
),
);
}
}

As you can see we are wrapping our NetworkAwareWidget inside a StreamProvider of NetworkStatus. StreamProvider also makes sure that on create it will subscribe to the NetworkStatusService controller stream.

Finally our app starting point main.dart will look something like this -

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_network_aware_app/ui/screens/home_screen.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData.dark().copyWith(primaryColor: Colors.blue),
home: Home());
}
}

The application would work as follows -

Online Offline Demo

I hope this helps you to build you own network aware app and components!

How to check internet connection globally and show no connection screen

In your MaterialApp widget, there is a builder. You can wrap your paths in any widget using the builder. Try doing this:

MaterialApp(
...
builder: (context, child) {
return StreamBuilder<ConnectivityResult>(
stream: InternetConnectionService().connectionStatusController.stream,
builder: (context, snapshot) {
final conenctivityResult = snapshot.data;
if (connectivityResult == ConnectivityResult.none || connectivityResult == null) return NoInternetScreen();

return child;
}
);
}
);

Now you don't have to add any internet logic in other files. You can simply write your build methods excluding them.

Check or listen continuously to internet connection/Network Connectivity in dart, flutter app

I had faced a similar problem a few weeks ago. This is a good approach. The internet_connection_checker plugin allows one to address issues at the network layer that the connectivity_plus plugin cannot address. I have carried out an implementation of these two plugins using the bloc library. For more information and code refer to this Stackoverflow post and this Github issue.

How to check currently internet connection is available or not in android

This will tell if you're connected to a network:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

boolean connected = (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED);

Warning: If you are connected to a WiFi network that doesn't include internet access or requires browser-based authentication, connected will still be true.

You will need this permission in your manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Android - Programmatically check internet connection and display dialog if notConnected

Finally, I got the answer.

ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null){
Description.setVisibility(View.INVISIBLE);
new AlertDialog.Builder(WelcomePage.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(getResources().getString(R.string.internet_error))
.setPositiveButton("OK", null).show();
}else{
dialog = ProgressDialog.show(WelcomePage.this, "", "Loading...", true,false);
new Welcome_Page().execute();
}


Related Topics



Leave a reply



Submit