Monitoring the WiFi on android device
I need suggestion on handling few Wifi scenarios in my application.
Suppose my application is running and device is kept idle for a while and it has gone into sleep mode. 开发者_如何学PythonIn the sleep mode the wifi is automatically turned off. Now again when the device is brought back from the sleep mode it takes some time to turn on the Wifi state. Now if during this time app background service is making http request, how we handle that scenario?
OR
suppose if Wifi is not available, device is trying to connect to the GPRS/3G and if during this period if user/background service is making the http request, how we handle it in the code?
You can list network interfaces, their type and connectivity status:
Get all network interfaces:
NetworkInfo[] networkInfos = ConnectivityManager.getAllNetworkInfo();
check type of network interface
networkInfo.getType() == ConnectivityManager.TYPE_MOBILE // or TYPE_WIFI
check status against
NetworkInfo.State
networkInfo.getState() == NetworkInfo.State.CONNECTED
If you need a connection then you can:
a. Check the network status as described above.
b. Register a Receiver to get update info when network connectivity changes: Intent action for network events in android sdk
If you try to get a HTTP data when there is no connectivity you will get an exception. You can catch this and retry later, but option 2. is better.
精彩评论