如何在 Android 中监控网络连接状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3307237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I monitor the network connection status in Android?
提问by Janusz
I have a Service that is downloading a file from a server. I warn the user to only download the file over Wireless LAN before the download starts.
我有一个正在从服务器下载文件的服务。我警告用户在下载开始之前只能通过无线局域网下载文件。
My problem is that my download gets stuck if I loose the network connection. Is there a way to listen for changes in network connection or if it is lost entirely?
我的问题是,如果我断开网络连接,我的下载就会卡住。有没有办法监听网络连接的变化或者它是否完全丢失?
回答by Pentium10
Listen for CONNECTIVITY_ACTION
This looks like good sample code. Here is a snippet:
这看起来是很好的示例代码。这是一个片段:
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w("Network Listener", "Network Type Changed");
}
};
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkStateReceiver, filter);