我用 DefaultHttpClient 和 HTTPGET 从服务器轮询数据。现在,假设用户在Wi-Fi网络和移动走出了房间。所以手机会自动开始使用3G网络。是否有任何回调对于这样的变化,我应该如何处理这样的变化。我应该重新开始投票还是操作系统照顾适当进行更改
I use DefaultHttpClient and HttpGet to poll data from server. Now, say a user was in Wi-fi network and moves out of the room. So the phone automatically starts using the 3G network. Are there any call-backs for such change, and how should I handle such changes. Should I start polling again or does the OS take care to make the changes appropriately
您可以设置一个接收器在你的清单:
You can set up a Receiver in your manifest:
<receiver
android:name=".NetworkChangeReceiver"
android:label="NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
和实施接收
像这样的东西:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
//Do something
if (mobile.isAvailable()) {
//Do something else
}
}
}
如果你保持一个持久连接它会往下走,你必须重新建立。
If you are keeping a persistent connection it will go down and you have to re-establish it.
如果您正在计划一个服务,你是不是保持连接的执着,你不会有问题。
If you are scheduling a service and you are not keeping the connection persistent, you will not have problems.