简体   繁体   English

如何检查Android中每个处理的Internet连接?

[英]How to check Internet Connection for every processing in Android?

In my application, most of the processing in all Activity need to connect to Server to get data. 在我的应用程序中,所有Activity中的大多数处理都需要连接到Server以获取数据。
So, where should I check the Internet connection? 那么,我应该在哪里检查Internet连接?
Is there any methods that can tell me when the connection is unavailable? 当连接不可用时,有什么方法可以告诉我?
Finally, how to implement it? 最后,如何执行呢? Is there any API for handle this case? 是否有用于处理这种情况的API?

use the ConnectivityManager class and Context.getSystemService(Context.CONNECTIVITY_SERVICE) method. 使用ConnectivityManager类和Context.getSystemService(Context.CONNECTIVITY_SERVICE)方法。 More information: http://developer.android.com/reference/android/net/ConnectivityManager.html 详细信息: http : //developer.android.com/reference/android/net/ConnectivityManager.html

// just checks if network connectivity is available 
public boolean isNetworkConnected(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) return true;
    return false;           
}//end method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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