简体   繁体   中英

Android - How to maintain 3g connection when wifi available

My app connects with a persistent connection to a server. If the device is currently using 3G it will connect over 3g.
The problem is that if it connected using 3G and moved into wifi the connection drops. How do I prevent it from disconnecting?

Sounds like the server is unable to accommodate clients seamlessly switching to a different IP address, or it may be using something like keep-alive packets to maintain connection state, and when the 3G connection drops, it disconnects your session.

This may not be something you have control over. From the Android point of view - the device will prefer WiFi depending on user preferences and you will likely not have any direct control over that either.

In a nutshell - if you can't modify or reconfigure the communications protocol to allow client IP changes on the fly, then there's nothing you can do with Android to mitigate the problem.

All mobile devices, and to a lesser extent, desktops/laptops will at some point change their public facing IP address, so it sounds like a bug or oversight in the server/protocol design to me.


EDIT:

In response to your comment, and in the interests of UX, you should be very careful about finding a way to force your app (possibly even the entire device) to remain on 3G when the user has requested that it use WiFi.

Most people have capped data plans with their device and wouldn't be very pleased if they think they are using WiFi (which is most likely free, or at least no additional cost) when in fact you've forced their device to continue using potentially very expensive 3G data instead.

This is especially important when any method would likely be actively circumventing the reasonable limits the Android environment presents you with, and therefore would probably not be flagged as a "Service that costs you money" when installed.


EDIT 2:

So, there may be a way for you to do it, but it relies on unsupported, private Android APIs which may change at any moment - usual disclaimer applies.

Take a look here where they access the ConnectivityManager object to allow you to enable mobile data.

This method does require you to build against the Android source tree, and use a shared user ID with "system" so may or may not be suitable, but these APIs are private (as apps are not supposed to be able to do this without user action), but it may help you.

This is how Android works. You're app should not maintain a persistent connection, it should only open a connection when needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM