views:

65

answers:

1

I have am having some issues with getting consistent results when checking if the network is available or not.

I use this code snippet inside a class AppPreferences to check the availability of a network.

/**
     * @return the networkAvailable
     */
    public boolean isNetworkAvailable() {
        connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        networkAvailable = connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isConnected();
        return networkAvailable;
    }

Before each run I set the context as below:

timer.scheduleAtFixedRate(

                new TimerTask() {

                    public void run() {

                        appPreferences.setContext(getBaseContext());

                        if (appPreferences.isNetworkAvailable()){

                            // perform task

                        }

                    }
                },
                0,
                UPDATE_INTERVAL);

I do know it is not tied to the background thread as I have a onReceive call doing the same logic and still this check fails.

It seems to predominantly happen when it moves between a cellular data connection and to wifi, or vice versa. The Context in which it was started seems to stay even though I update it.

Does anyone have any idea what could be the issue here?

A: 

It seems as if the active network info will stay on the state of when the Context of the Service/Activity/Receiver is started. Hence if you start it on a network, and then later disconnect from that (i.e. moves from 3G to Wifi and disconnect the 3G connection) it will stay on the first active connection making the app believe the phone is offline even though it is not.

It seems to me that the best solution is to user getApplicationContext instead as that will not be tied to when you started the particular "task".

Update: Related is that if you run applications on Androids (in particular Nexus One) for a long period of time when connected to Wifi do check that you make sure you do not let the Wifi sleep when the screen sleeps. You will be able to set that at the Advanced option under Wireless Networks.

Erik