prathik
prathik

Reputation: 129

open Android app when internet connection is on otherwise display no internet connection message

I just created an android app for fetching data from a website. I want to check if the device has an internet connection or not. If the device has internet connection, run my code and fetch the data and display it, otherwise if the device has no internet, then display the no internet connection message. I have tried this code to check the internet connection. How can I call the code when there is an internet connection?

My Java code:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_primary);
        new FetchWebsiteData().execute();        
            }
        });

    }

    private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
        String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
        ProgressDialog progress;
        private Context context;

        //check Internet connection.
        private void checkInternetConnection(){

            ConnectivityManager check = (ConnectivityManager) this.context.
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            if (check != null)
            {
                NetworkInfo[] info = check.getAllNetworkInfo();
                if (info != null)
                    for (int i = 0; i <info.length; i++)
                        if (info[i].getState() == NetworkInfo.State.CONNECTED)
                        {
                            Toast.makeText(context, "Internet is connected",
                                    Toast.LENGTH_SHORT).show();

                        }

            }
            else{
                Toast.makeText(context, "not conencted to internet",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //some code here
        }

        @Override
        protected String[] doInBackground(Void... params) {
            ArrayList<String> hrefs=new ArrayList<String>();
            try {

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            //get the array list values
            for(String s:hrefs)
            {
                //some code
            }
            //parsing first URL
            String [] resultArray=null;
            try {


            } catch (IOException e) {
                e.printStackTrace();
            }
            //parsing second URL
            String [] resultArray1=null;
            try {



            } catch (IOException e) {
                e.printStackTrace();
            }

            try{


            } catch (Exception e) {
                e.printStackTrace();
            }


            return null;
        }



        @Override
        protected void onPostExecute(String[] result) {

            ListView list=(ListView)findViewById(R.id.listShow);
            ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
            list.setAdapter(arrayAdapter);
            mProgressDialog.dismiss();
        }
    }
}

How can I run the code when the connection is open and how to display message when app has no internet connection?

Upvotes: 8

Views: 6661

Answers (9)

parithi
parithi

Reputation: 270

try this

//check internet connection
public static boolean isNetworkStatusAvialable (Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null)
    {
        NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
        if(netInfos != null)
        {
            return netInfos.isConnected();
        }
    }
    return false;
}

once the method return the value you have to check

//detect internet and show the data
    if(isNetworkStatusAvialable (getApplicationContext())) {
        Toast.makeText(getApplicationContext(), "Internet detected", Toast.LENGTH_SHORT).show();
        new FetchWebsiteData().execute();
    } else {
        Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();

    }

Upvotes: 8

kgandroid
kgandroid

Reputation: 5595

Create a class NetworkInformation.java

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkInformation {

     private static NetworkInfo networkInfo;

     public static boolean isConnected(Context context) {

             ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

             try{
                networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // test for connection for WIFI
            if (networkInfo != null
                    && networkInfo.isAvailable()
                    && networkInfo.isConnected()) {
                return true;
            }

            networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            // test for connection for Mobile
            if (networkInfo != null
                    && networkInfo.isAvailable()
                    && networkInfo.isConnected()) {
                return true;
            }

            return false;
      }   

}

Now check whether network is available or not before calling an asynctask like this:

if(NetworkInformation.isConnected(YourClassName.this))
        {
             new FetchWebsiteData().execute();        
        }else{

            Toast.makeText(NewsAndEvents.this,R.string.no_connection,Toast.LENGTH_LONG).show();
        }

Dont forget to include the below permissions in AndroidManifest.xml:

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

Upvotes: 2

Stopfan
Stopfan

Reputation: 1757

Here is class to get information about your internet connection https://gist.github.com/emil2k/5130324

Just copy and paste in your code and use it's methods

Upvotes: 3

Anas Ahamed
Anas Ahamed

Reputation: 206

//Implement this code in MainActivity and check if isConnectingToInternet(), then allow Otherwise show the No Internet Connection message.

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;
        }

Upvotes: 1

Soroush
Soroush

Reputation: 126

To check if user connect to the wifi or any access point it's better to check this method first to see if user has any connection or not and if it returns true you can check if he has real connection or not with next method

    public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

to check if user has real traffic to send request over network

be aware that you shouldn't call hasTraffic() method in main thread (you can use AsyncTask )

public static boolean hasTraffic(){

    try {

        URL url = new URL("http://www.google.com/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        urlc.setRequestProperty("User-Agent", "test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(2000); // mTimeout is in seconds
        urlc.connect();
        if (urlc.getResponseCode() == 200) {
            Log.d("check Traffic ", "has traffic");
            return true;
        } else {
            return  false;
        }
    } catch (Exception e) {
        Log.i("warning", "Error checking internet connection", e);
        return  false;
    }

}

TO check internet connection

        new AsyncTask<Void, Void, Boolean>() {
        @Override
        protected void onPostExecute(Boolean flag) {

            if(flag == true){
                // do whatever you want
            }else{
                cantAccessToService();
            }
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            if(isOnline(SplashActivity.this) && hasTraffic() ){
                return true ;
            }else{
                return false ;
            }
        }
    }.execute();

Upvotes: 1

Ravindra Kushwaha
Ravindra Kushwaha

Reputation: 8042

Use below code and make a class like NetworkAvailablity.java

public class NetworkAvailablity {

    public static boolean checkNetworkStatus(Context context) {
        boolean HaveConnectedWifi = false;
        boolean HaveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    HaveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    HaveConnectedMobile = true;
        }

        return HaveConnectedWifi || HaveConnectedMobile;
    }
}

And in the your code use these following lines which check that internet is available or not

        if (NetworkAvailablity.checkNetworkStatus(getActivity())) {
             //code here 
        }
        else
        {
        // give message here by Toast or create the alert dilog 
             Toast.makeText(context, "No network is available",Toast.LENGTH_LONG).show();
        }

Upvotes: 1

Karthika PB
Karthika PB

Reputation: 1373

use this method for checking network availability

public static boolean isNetworkAvailable(Context context) {



    try{
    ConnectivityManager connectivityManager 
          = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    boolean s= activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

        return s;
    }
    catch(Exception e){

        System.out.println("exception network"+e);
        return false;
    }
}

if it returns true you can go ahead with network call else Toast a message of network unavailablity.

Upvotes: 2

Jain Nidhi
Jain Nidhi

Reputation: 255

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;
}

Upvotes: 4

Tim Mutton
Tim Mutton

Reputation: 756

https://stackoverflow.com/a/9570292/4241807 tells you how to check for network connectivity, then just place your message in the "else" part of the code

Upvotes: 1

Related Questions