Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 775
prathik Avatar asked Apr 22 '15 06:04

prathik


People also ask

Why does my apps keep saying no internet connection?

Restart your device. If restarting doesn't work, switch between Wi-Fi and mobile data: Open your Settings app and tap Network & internet or Connections. Depending on your device, these options may be different. Turn Wi-Fi off and mobile data on, and check if there's a difference.

Why does my phone say not connected to the Internet when playing games?

Answer: It may be that the Internet connection is not detected. Stopping the game from the taskbar and restarting it while the Internet connection is enabled should solve this problem. If it doesn't, please turn off your device for 2 minutes, restart it, re-establish the Internet connection and then launch the game.

How does your app check that internet connectivity is available in the manifest?

In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object. Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.


4 Answers

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();

    }
like image 71
parithi Avatar answered Sep 27 '22 22:09

parithi


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;
}
like image 41
Jain Nidhi Avatar answered Sep 27 '22 23:09

Jain Nidhi


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

like image 45
Stopfan Avatar answered Sep 28 '22 00:09

Stopfan


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.

like image 42
Karthika PB Avatar answered Sep 28 '22 00:09

Karthika PB