在Android设备上监控WiFi

4
我需要在我的应用程序中处理几个Wifi场景,希望得到建议。
假设我的应用程序正在运行且设备空闲一段时间并进入睡眠模式。在睡眠模式下,Wifi会自动关闭。现在,当设备从睡眠模式恢复时,打开Wifi状态需要一些时间。 如果在此期间应用程序后台服务正在进行http请求,我们如何处理这种情况?
或者,假设Wifi不可用,设备正在尝试连接到GPRS/3G,如果在此期间用户/后台服务正在进行http请求,我们如何在代码中处理它?
1个回答

2
  1. 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
    
  2. 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

  3. 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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接