bhagyasri patel
bhagyasri patel

Reputation: 61

how to check availability of internet and server(url) in android

I have developed my application in android for weather forecasting. In my application when my internet is not working or server is not reachable (given on the URL) ,the application gets crashed with the message "Unfortunately, application is stopped". Here I have posted my code. I don't understand where I have to handle this exception. please help me..Thanks in advance...

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(isNetworkAvailable())
        {
        setContentView(R.layout.activity_location);
        weatherlist = new ArrayList<HashMap<String, String>>();

        // Getting complete weather details in background thread
        new GetWeatherDetails().execute();
        new GetWeatherDetails1().execute();
        // Get listview
                ListView lv = getListView();

                // on seleting single product
                // launching Edit Product Screen
                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        // getting values from selected ListItem
                        String FC_DATE = ((TextView) view.findViewById(R.id.fc_date)).getText()
                                .toString();

                        // Starting new intent
                        Intent in = new Intent(getApplicationContext(),
                                ForecastActivity.class);
                        // sending pid to next activity

                        in.putExtra(TAG_FC_DATE, FC_DATE);
                        in.putExtra(TAG_LAT, LAT);
                        in.putExtra(TAG_LONG, LONGITUDE);
                        // starting new activity and expecting some response back
                        startActivityForResult(in, 100);
                    }
                });

            }
        else
        {
            Toast.makeText(this, "Network unavailable", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        LocationActivity.this, weatherlist,
                        R.layout.list_item, new String[] { TAG_FC_DATE},
                        new int[] { R.id.fc_date });

                // updating list view
                setListAdapter(adapter);
            }
        });

    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

Upvotes: 0

Views: 486

Answers (3)

FriendlyAgent
FriendlyAgent

Reputation: 171

First add a check to see if the phone is connected to a Netwerk.

You can do this using the following code;

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

if (isNetwork()) {
    // do your request && server ping !!
} else {
    Toast.makeText(this, "Not connected to a network", Toast.LENGTH_SHORT).show();
}

Also add the following permission to the AndroidManifest.xml:

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

However, it can return a false positive for example, if the phone is connected to a WiFi network with a captive portal or vpn, this function will incorrectly return true.

That's why you still need to check if you have internet, you can do this by adding a simple ping to your server or Google (Because Google is up 99,99% of the time).

Something like this;

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

public Boolean isInternet() {
    try {       
        Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");      
        int returnVal = process.waitFor();      
        boolean reachable = (returnVal==0);
        return reachable
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false; 
}

if (isNetwork()) {
    if (isInternet()) {
        // do your request
    } else {
        Toast.makeText(this, "No internet connection", Toast.LENGTH_SHORT).show();
    }
else {
    Toast.makeText(this, "Not connected to a network", Toast.LENGTH_SHORT).show();
}

Finally dont forget, when you're doing a async tasks, you update the GUI in the onPostExecute Method. You dont call the runOnUiThread() in doInBackground.

Some documentation explaining this;

http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 0

Chackle
Chackle

Reputation: 2269

Use the following method to check if internet is available

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Then call it like this and display a message to your user. I've included a Toast, but you may want to use a dialog of some sort

if (isNetworkAvailable())
{
    // do your request
}
else
{
    Toast.makeText(this, "Network unavailable", Toast.LENGTH_SHORT).show();
}

To get getActiveNetworkInfo() to work you need to add the below permission to the manifest file.

uses-permission android:name="android.permission.INTERNET"
   uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

Also, when you're doing async tasks, you should be updating the UI in the onPostExecuted method of the AsyncTask Class. Provided the method below, put this in the same scope as your doInBackground of your Async Task:

@Override
protected void onPostExecute(String result) {
    // parse your response here and update the UI with the data parsed.
}

Upvotes: 1

Jay Rathod
Jay Rathod

Reputation: 11245

Use This Method.

public static boolean isInternetAvailable(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }
}

Upvotes: 0

Related Questions