This is not a duplicate
I want to check real-time internet connection from my activity using AsyncTaskand Handler to display or hide TexView if a connection is available or not. But it doesn't work.
My code throws NetworkOnMainThreadException even using AsyncTask
I'm using this code:
class CheckNetWorkConnection extends AsyncTask<String, Void,Boolean>{
MyActivity activity;
public checkNetWorkConnection(MyActivity activity) {
this.activity= activity;
}
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible;
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
}
});
// doInBackground always retun false
return networkAvalaible;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
// Using handler to repeat Task
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (aBoolean){
activity.noConnection.setVisibility(View.GONE);
}else {
activity.noConnection.setVisibility(View.VISIBLE);
}
}
},3000);
super.onPostExecute(aBoolean);
}
}
to use it, you call
new CheckNetWorkConnection().execute();
you will want your async task to run indefinitely until an internet connection is lost. your current code will only check one time.
you need to change your codes to be polling for it to work.
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible = false;
do {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
sleep(5000); //check connection every 5 seconds.
// you can call publish progress here to tell your process that
// connection is available
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
} while (networkAvalaible);
//you only exit and asyncTask when connection is lost.
return networkAvalaible;
}
AsyncTask is not the right way to do it though... take a look at the following article below.
https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
Put this Class into your util Package to chack internet connection anywhere into your project.
ConnectionDetector.java
package util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by Pranav on 29/08/16.
*/
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;
}
}
Here is a code snippet if MainActivity.java to check internet connection and if internet connection is on then call asynctask otherwise give toast message.
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
import util.ConnectionDetector;
/**
* Created by Pranav on 29/08/16.
*/
public class CaseDetaiksActivity extends Activity {
public static Context context;
ConnectionDetector mConnectionDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
mConnectionDetector = new ConnectionDetector(context);
setContentView(R.layout.activity_mail);
if (mConnectionDetector.isConnectingToInternet()) {
MyAyncTask MyTask = new MyAyncTask();
MyTask.execute();
} else {
Toast.makeText(context, getString(R.string.please_check_internet), Toast.LENGTH_SHORT).show();
}
}
public static class MyAyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// You can track you progress update here
}
#Override
protected Void doInBackground(Void... params) {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
}
return null;
}
}
}
Hope this helps you
a .Create a broadcast receiver class
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if(checkInternet(context)){
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}
}
public boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}
}
b. Create a Service manager class
public class ServiceManager {
Context context;
public ServiceManager(Context base) {
context = base;
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
Register permissions in the Android Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Declare Broadcast Receiver in the Android Manifest
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
In your activity :
a. register your broadcast receiver in onResume()
registerReceiver(new NetworkChangeReceiver() , new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
b. unregister your broadcast receiver in onPause();
unregisterReceiver(new NetworkChangeReceiver());
Related
Explanation:
Hello Everyone, I am trying to check my device is connected with internet or not. I am explaining all the step what i do.
Step-1: I have created a receiver class to check when the connection status change.
Step-2: I also created a Interface in which i have method to get the connection status (true/false)
Step-3: Implement this listener on my Activity and then override the listener method.
Step-4: If my internet is connected then go ahead. If my internet is not connected i put the message your internet is not connected.
Step-5: Finally i register this receiver in AndroidManifest.xml file.
Note: All above step is working fine until SDK_VERSION Marshmallow. When i checked it with Nougt(7.0) then it's not working.
Receiver
public class ConnectivityReceiver extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver(){
super();
}
#Override
public void onReceive(Context context, Intent intent) {
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(Utils.isInternetConnected(context));
}
}
public static boolean isConnected(Context context) {
if(Utils.isInternetConnected(context)){
return true;
}else{
return false;
}
}
}
Listener
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
Internet connection status method
public static boolean isInternetConnected(final 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 true;
} else {
return false;
}
}
Permission and register receiver in Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<receiver
android:name="com.durian.receivers.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Below method is check internet connetion
private boolean checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected(CustomerActivity.this);
showSnack(isConnected);
return isConnected;
}
Below method is check isconnected or not
private void showSnack(boolean isConnected) {
String message;
int color;
Snackbar snackbar;
if (isConnected) {
Toast.make(getActivity(),"CONNECTED",Toast.LENGTH_SHORT).show();
} else {
Toast.make(getActivity(),"Disconnected",Toast.LENGTH_SHORT).show();
}
}
Below method call the listener
#Override
protected void onResume() {
super.onResume();
AppController.getInstance().setConnectivityListener(this);
}
Here is my Application class which register in android with name parameter
public class AppController extends Application{
public static final String TAG=AppController.class.getSimpleName();
public static Typeface fntGabriola;
public static Typeface fntRalewayLight;
public static Typeface fntRalewayMedium;
public static Typeface fntRalewayRegular;
public static Typeface fntRalewaySemiBold;
public static Typeface fntsegoeuRegular;
public static Typeface fntsegoeuLight;
public static Typeface fntsegoeSemiBold;
public static Typeface fntModerneSans;
public static Typeface fntMordernist;
public static Typeface fntOpenSans;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
Fabric.with(this, new Crashlytics());
fntGabriola=Typeface.createFromAsset(getAssets(),"fonts/Gabriola.ttf");
fntRalewayLight=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Light.ttf");
fntRalewayMedium=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Medium.ttf");
fntRalewayRegular=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Regular.ttf");
fntRalewaySemiBold=Typeface.createFromAsset(getAssets(),"fonts/Raleway-SemiBold.ttf");
fntsegoeuRegular=Typeface.createFromAsset(getAssets(),"fonts/segoeui.ttf");
fntsegoeuLight=Typeface.createFromAsset(getAssets(),"fonts/segoeuil.ttf");
fntsegoeSemiBold=Typeface.createFromAsset(getAssets(),"fonts/seguisb.ttf");
fntModerneSans=Typeface.createFromAsset(getAssets(),"fonts/moderne_sans.ttf");
fntMordernist=Typeface.createFromAsset(getAssets(),"fonts/Sk-Modernist-Regular.otf");
fntOpenSans=Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Regular.ttf");
}
public static synchronized AppController getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
Note: Everything is working fine below the nought OS Version. But the problem is when i test in nought it is not working. Please give a proper solutions which working in all the OS.
For reference you can check the snapdeal application
I want exactly as in snapdeal Android application.
/**You can simply use below code Snippet**/
/**Below code Check 2 condition that Your device is connected to Wifi or Data - Connection or not. If yes then will also check that Internet is working or not..**/
/**ConnectivityReceiver Class**/
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectivityReceiver
{
private static ConnectivityReceiver.AsyncResponse asyncResponse;
/************************************************ for checking internet connection*******/
public static boolean isNetworkAvailable(Context context)
{
ConnectivityManager connectivity = null;
boolean isNetworkAvail = false;
try
{
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;
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (connectivity != null)
{
connectivity = null;
}
}
return isNetworkAvail;
}
private static class ConnectionCheck extends AsyncTask<String,Void,Boolean>
{
#Override
protected Boolean doInBackground(String... params)
{
HttpURLConnection urlConnection = null;
try
{
if(params[0].endsWith("") || params[0] == null)
{
params[0] = "http://www.google.com/";
}
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (!url.getHost().equals(urlConnection.getURL().getHost()))
{
// we were redirected! Kick the user out to the browser to sign on?
return true;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
finally
{
urlConnection.disconnect();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean)
{
super.onPostExecute(aBoolean);
asyncResponse.processFinish(aBoolean);
}
}
public interface AsyncResponse
{
void processFinish(boolean output);
}
public static void speedTest(String url,ConnectivityReceiver.AsyncResponse asyncResponse)
{
ConnectivityReceiver.asyncResponse = asyncResponse;
new ConnectivityReceiver.ConnectionCheck().execute(url);
}
}
/**Code implementation in your class**/
String ConnectionCheck_Url = "http://www.google.com/";
if(ConnectivityReceiver.isNetworkAvailable(MainActivity.this))
{
ConnectivityReceiver.speedTest(ConnectionCheck_Url,new ConnectivityReceiver.AsyncResponse()
{
#Override
public void processFinish(boolean output)
{
if (output)
{
/* * If The output Value --->"True" Then Only
request will Execute
* NOTE: Here "True" Value Means Intenet is Working*/
// Implement your code here
}
else
{
//Please_Check_Your_Internet_Connection
}
}
});
}
else
{
// Please_Connect_to_your_Wifi_or_Data_Connection
}
}
/**Android MainifestFile.xml**/
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
I have searching for a fast and effective method to check the internet connection, and i found that its better to ping google to find the internet connection status.But I found a number of ways to ping google and i am confused which one to use out of all Those.Below are the methods that i saw.
Method 1 :
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Method 2 :
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) {
e.printStackTrace();
}
return false;
}
Method 3 :
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
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();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
Method 4 :
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) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
Which one i should choose?? I need a faster and effective method.
You can try to check if host is available with InetAddress.getByName(host).isReachable(timeOut). It should be same as checking if connection is valid.
Check documentation for more info.InetAddress
I'm using broadcast to check the connection every time. Create a class for connection info.
import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectivityStatus extends ContextWrapper{
public ConnectivityStatus(Context base) {
super(base);
}
public static boolean isConnected(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo connection = manager.getActiveNetworkInfo();
if (connection != null && connection.isConnectedOrConnecting()){
return true;
}
return false;
}
}
Apply code into your Activity:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(!ConnectivityStatus.isConnected(getContext())){
// no connection
}else {
// connected
}
}
};
Register broadcast in your activity's onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
..
...
....
}
Don't forget to unregistered/register on Activity cycle:
#Override
protected void onResume() {
super.onResume();
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
your_activity_context.unregisterReceiver(receiver);
}
Well, after my SplashScreen screen. My app will check for an Internet connection. if there is internet available, it will call the WebView. Otherwise, it will call one Activity of error.
But how do I pair to check the internet DURING SplashScreen?
ACTIVITY SPLASH SCREEN:
public class Splash extends Activity{
private static int tempo_splash = 1000;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Para o layout preencher toda tela do cel (remover a barra de tit.)
new Timer().schedule(new TimerTask() {
public void run() {
finish();
Intent intent = new Intent();
intent.setClass(Splash.this, MainActivity.class); //Chamando a classe splash e a principal (main)
startActivity(intent);
}
}, 2000);
}
}
MY CLASS CheckINTERNET:
public class CheckInternet extends Activity{
boolean status = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internet);
Button btnStatus = (Button) findViewById(R.id.check_btn);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = checkInternetConnection();
if (status) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(CheckInternet.this, MainActivity.class);
CheckInternet.this.startActivity(mainIntent);
CheckInternet.this.finish();
}
}, 5000);
}
else {
Toast.makeText(getApplicationContext(), "You don't have Internet connection. Try Again", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean checkInternetConnection() {
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] inf = connectivity.getAllNetworkInfo();
if (inf != null) {
for (int i = 0; i < inf.length; i++) {
return true;
}
}
}
return false;
}
}
try this code... maybe help you
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.splash_screen);
if(isWorkingInternetPersent()){
splash();
}
else{
showAlertDialog(SplashScreen.this, "Internet Connection",
"You don't have internet connection", false);
}
}
public void splash() {
Thread timerTread = new Thread() {
public void run() {
try {
sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(getApplicationContext(), New_Main_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
};
timerTread.start();
}
public boolean isWorkingInternetPersent() {
ConnectivityManager connectivityManager = (ConnectivityManager) getBaseContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// alertDialog.setIcon((status) ? R.mipmap.ic_launcher : R.mipmap.ic_launcher);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
});
// Showing Alert Message
alertDialog.show();
}
You should not really have an Intent just for checking connectivity. My suggestion is to create a "utility" class - call is MyConnectivityChecker and in there you add a static method (isConnected) with the following code:
public class MyConnectivityChecker {
public static boolean isConnected(Context context){
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
connected = (wifi.isAvailable() && wifi.isConnectedOrConnecting() || (mobile.isAvailable() && mobile.isConnectedOrConnecting()));
return connected;
}
}
Then in your Splash Activity wherever you want to check connectivity, you call the isConnected method like this:
MyConnectivityChecker.isConnected(this)
For example you could do something like this:
if(MyConnectivityChecker.isConnected(this)){
//connectivity available
}
else{
//no connectivity
}
I hope this helps. Give it a try and let me know.
what you can do is check for internet connection inside of your timer of SplashScreen.
new Timer().schedule(new TimerTask() {
public void run() {
if(isOnline()){
Intent intent = new Intent(Splash.this,WebViewActivity.class);
startActivity(intent);
finish();
}else{
Intent intent = new Intent(Splash.this,ErrorActivity.class);
startActivity(intent);
finish();
}
}
}, 2000);
And for internet checking you can use this method.
public boolean isOnline() {
System.out.println("executeCommand");
Runtime localRuntime = Runtime.getRuntime();
try {
int i = localRuntime.exec("/system/bin/ping -c 1 8.8.8.8")
.waitFor();
System.out.println(" mExitValue " + i);
boolean bool = false;
if (i == 0) {
bool = true;
}
return bool;
} catch (InterruptedException localInterruptedException) {
localInterruptedException.printStackTrace();
System.out.println(" Exception:" + localInterruptedException);
return false;
} catch (IOException localIOException) {
localIOException.printStackTrace();
System.out.println(" Exception:" + localIOException);
}
return false;
}
NOTE: Add this method in your SplashScreen outside the onCreate() methode.
Happy Coding..
Create Following Utility Class as below :
public class Utility {
/**
* This function check <u>Mobile Data</u> or <u>WiFi</u> is switched on or not..<br />
* It will be return <b>true</b> when switched on and return <b>false</b> when switched off.<br />
* <br />
* Developed by <b>Suthar Rohit</b>
*
* #param context {#link Context} of activity
* #return true if <u>Mobile Data</u> or <u>WiFi</u> is switched on.
*/
public static boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
return nInfo != null && nInfo.isConnected();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
and use as below in splash screen :
if(Utility.isOnline()) {
// INTERNET AVAILABLE
} else {
// INTERNET NOT AVAILABLE
}
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
public class SplashACtivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
NetworkInfo activeNetwork = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
// Load Webview
startActivity(new Intent(SplashACtivity.this, WebViewActivity.class));
} else {
// Show No internet
startActivity(new Intent(SplashACtivity.this, NoInternetACtivity.class));
}
}
}, 5000);
}
}
I have the following code, and what I'm trying to do is to programmatically check if there is an internet connection or not.
Since I'm getting a NetworkOnMainThreadException, and have been advised to use AsyncTask.
I want to perform network operation on hasActiveInternetConnection(Context context)and return true if connected to a network, else false .
How do I do this using AsyncTask?
public class NetworkUtil extends AsyncTask<String, Void, String>{
Context context;
public NetworkUtil(Context context){
this.context = context;
}
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(context).isNetworkAvailable())
{
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();
boolean url= (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException e) {
}
}
// your get/post related code..like HttpPost = new HttpPost(url);
else {
Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
use this class for checking internet connectivity...
public class CheckNetwork {
private Context context;
public CheckNetwork(Context context) {
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
then.....
use the this ASynTask for httppost.
public class NetworkUtil extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) {
// your get/post related code..like HttpPost = new HttpPost(url);
} else {
// No Internet
// Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
There is no way to get an Internet connexion state, you will always have the network connection state.
But I found a pretty nice answer here: you send a request to google.com !! :) you can also try to ping to google by unix commandes if you want !!
here the guy is using a thread , and waiting a little bit for the answer, then returning a boolean . you do your staff in the handler . this is his code :
public static void isNetworkAvailable(final Handler handler, final int timeout) {
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in milliseconds)
new Thread() {
private boolean responded = false;
#Override
public void run() {
// set 'responded' to TRUE if is able to connect with google mobile (responds fast)
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
}
catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0); }
else { handler.sendEmptyMessage(1); }
}
}
}.start();
}
Then, I define the handler:
Handler h = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
...and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
Your AsyncTask should look like this:
private class NetworkUtilTask extends AsyncTask<Void, Void, Boolean>{
Context context;
public NetworkUtilTask(Context context){
this.context = context;
}
protected Boolean doInBackground(Void... params) {
return hasActiveInternetConnection(this.context);
}
protected void onPostExecute(Boolean hasActiveConnection) {
Log.d(LOG_TAG,"Success=" + hasActiveConnection);
}
}
You would then execute it like the following:
NetworkUtilTask netTask = new NetworkUtilTask(context);
netTask.execute();
Is there an Android Intent ACTION_XXX that notifies me when an Internet Connection is available?
I want to instantiate a BroadcastReceiver that notifies my application when a user enables Internet Connection (by wifi, by GSM, etc.)
Could anyone help me?
<receiver android:name=".YOURRECEIVER">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Accepted answer is correct. I only add Receiver code for completion:
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("app","Network connectivity change");
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
Log.i("app","Network "+ni.getTypeName()+" connected");
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
Log.d("app","There's no network connectivity");
}
}
}
Update to #lujop answer:
public class NetworkStateReceiver extends BroadcastReceiver {
private static final String TAG = "NetworkStateReceiver";
#Override
public void onReceive(final Context context, final Intent intent) {
Log.d(TAG, "Network connectivity change");
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
Log.i(TAG, "Network " + ni.getTypeName() + " connected");
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.d(TAG, "There's no network connectivity");
}
}
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(isConnected(context)) Toast.makeText(context, "Connected.", Toast.LENGTH_LONG).show();
else Toast.makeText(context, "Lost connect.", Toast.LENGTH_LONG).show();
}
public boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
UPDATE
If your app targets API level 26 or higher, you cannot use the
manifest to declare a receiver for implicit broadcasts (broadcasts
that do not target your app specifically), except for a few implicit
broadcasts that are exempted from that restriction. In most cases, you
can use scheduled jobs instead.
usage
connection = MyReceiver()
// onCreate - onDestroy, onResume - onPause depends on you
override fun onStart() {
super.onStart()
registerReceiver(connection, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
override fun onStop() {
super.onStop()
// remember unregister to avoid leak
unregisterReceiver(connection)
}
UPDATE 2
CONNECTIVITY_ACTION This constant was deprecated in API level 28.
apps should use the more versatile requestNetwork(NetworkRequest, PendingIntent), registerNetworkCallback(NetworkRequest, PendingIntent) or registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback) functions instead for faster and more detailed updates about the network changes they care about.
because it added in API level 22, so above code will work fine on all versions of android
The missing part of all answers is a reminder to register for that action:
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(your_receiver, filter);
This code will work (in all versions) as the manifest registration will not work for 7+(API 25 and above) devices see this link.
private void foo(){
registerReceiver(connectionBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver connectionBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getExtras() == null)
return;
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
// connected
}
}
};
I'm using broadcast to check the connection every time. Create a class for connection info.
import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectivityStatus extends ContextWrapper{
public ConnectivityStatus(Context base) {
super(base);
}
public static boolean isConnected(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo connection = manager.getActiveNetworkInfo();
if (connection != null && connection.isConnectedOrConnecting()){
return true;
}
return false;
}
}
Apply code into your Activity:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(!ConnectivityStatus.isConnected(getContext())){
// no connection
}else {
// connected
}
}
};
Register broadcast in your activity's onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
..
...
....
}
Don't forget to unregistered/register on Activity cycle:
#Override
protected void onResume() {
super.onResume();
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
your_activity_context.unregisterReceiver(receiver);
}
Continuing meow mwo's Answer
you can enable/disable the receiver by:
enable
ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
}
disable
ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
}
where, the same can be called in an Intent or in onCreate
NetworkInfo.isConnected() is unreliable method to test for internet status, it will return true when there is a network connection even though it may have no internet access (ex. wifi with no internet). A more reliable approach would be to use ping with a CONNECTIVITY_ACTION BroadcastReceiver:
private void registerInternetReceiver()
{
if (this.internetReceiver != null) return;
this.internetReceiver = new BroadcastReceiver()
{
#Override
public void onReceive (Context context, Intent intent)
{
if (isInternetAvailable()) Log.i ("Tag", "internet status online");
else Log.i ("Tag", "internet status offline");
}
};
IntentFilter filter = new IntentFilter();
filter.addAction (ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver (internetReceiver, filter);
}
private boolean isInternetAvailable()
{
try
{
return (Runtime.getRuntime().exec ("ping -c 1 google.com").waitFor() == 0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return false;
}
**Also worked on above Android 7.0**
// AndroidManifest.xml
<service
android:name=".NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
// MyApplication.java
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
public class MyApplication extends Application {
private static Context context;
public static Context getContext() {
return context;
}
public static final String TAG = MyApplication.class.getSimpleName();
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
mInstance = this;
scheduleJob();
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
private void scheduleJob()
{
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
assert jobScheduler != null;
jobScheduler.schedule(myJob);
}
}
// Constants.java
public class Constants {
public static final String CONNECT_TO_WIFI = "WIFI";
public static final String CONNECT_TO_MOBILE = "MOBILE";
public static final String NOT_CONNECT = "NOT_CONNECT";
public final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
}
// LiveConnectivityReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class LiveConnectivityReceiver extends BroadcastReceiver {
private MConnectivityReceiver mConnectivityReceiver;
LiveConnectivityReceiver(MConnectivityReceiver listener) {
mConnectivityReceiver = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiver.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface MConnectivityReceiver {
void onNetworkConnectionChanged(boolean isConnected);
}
}
// MainActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStop() {
stopService(new Intent(this, NetworkSchedulerService.class));
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
startService( new Intent(this, NetworkSchedulerService.class));
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.mReceiver);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter("android.intent.action.MAIN");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isConnection = intent.getBooleanExtra("VALUE", false);
if (!isConnection) {
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Back to online", Toast.LENGTH_SHORT).show();
}
}
};
this.registerReceiver(mReceiver, intentFilter);
}
}
// NetworkSchedulerService.java
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.content.IntentFilter;
public class NetworkSchedulerService extends JobService implements LiveConnectivityReceiver.ConnectivityReceiverListener
{
private LiveConnectivityReceiver mLiveConnectivityReceiver;
#Override
public void onCreate()
{
super.onCreate();
mLiveConnectivityReceiver = new LiveConnectivityReceiver(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
registerReceiver(mLiveConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
unregisterReceiver(mLiveConnectivityReceiver);
return true;
}
#Override
public void onNetworkConnectionChanged(boolean isConnected)
{
Intent broadcastedIntent=new Intent("android.intent.action.MAIN");
broadcastedIntent.putExtra("VALUE", isConnected);
sendBroadcast(broadcastedIntent);
}
}
From Android 7++, #fedj's answer will not work but you can register the broadcast receiver programmatically.
Apps targeting Android 7.0 (API level 24) and higher do not receive
CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver
in their manifest. Apps will still receive CONNECTIVITY_ACTION
broadcasts if they register their BroadcastReceiver with
Context.registerReceiver() and that context is still valid.
I would read the docs updated for nougat + , because intent is deprecated due to the # of devices, network info alone is not sufficient. I would use connectivity manager ( connectivity action, add variables there) commands and vars there, because most has changed in the last year alone, and on for testing, enable cell data always active, verbose logging and aggressive handover, use wlan filter if needed:
https://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION
**You can put this line of code on Helper Methods and call it when you want to check internet connection **
public static class InternetState {
static ConnectivityManager cm;
static public boolean isConnected(Context context) {
try {
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (NullPointerException e) {
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
}