NetworkAvailability check returns false yet the phone is online

风流意气都作罢 提交于 2019-12-08 05:38:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3283828/networkavailability-check-returns-false-yet-the-phone-is-online

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!