【发布时间】:2016-08-31 22:54:15
【问题描述】:
当我通过网络服务将我的数据上传到服务器时,我必须在上传数据之前检查互联网连接,这可能会花费我的时间(我使用 asyntask 来检查带有进度对话框的互联网连接),即使用户可能会感觉很多加载中谁能告诉我哪种方法是检测互联网连接的最佳方法。
【问题讨论】:
标签: android connection connectivity
当我通过网络服务将我的数据上传到服务器时,我必须在上传数据之前检查互联网连接,这可能会花费我的时间(我使用 asyntask 来检查带有进度对话框的互联网连接),即使用户可能会感觉很多加载中谁能告诉我哪种方法是检测互联网连接的最佳方法。
【问题讨论】:
标签: android connection connectivity
您可以使用以下方法来验证数据连接是否可用:
public static boolean isDataConnectionAvailable(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
如果返回 true,则有可用的数据连接。
还要确保将其添加到清单中:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
【讨论】:
public static NETWORK_AVAILABILITY_STATUS getAvailableNetworkType(Context context)
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting())
{
int type = activeNetworkInfo.getType();
if (type == ConnectivityManager.TYPE_MOBILE)
{
return NETWORK_AVAILABILITY_STATUS.DATA_PLAN;
}
else if (type == ConnectivityManager.TYPE_WIFI)
{
return NETWORK_AVAILABILITY_STATUS.WIFI;
}
}
return NETWORK_AVAILABILITY_STATUS.NO_NETWORK;
}
注意:您需要有互联网权限,即
<uses-permission android:name="android.permission.INTERNET" />
注意:此方法不保证网络可达,连接可能仍然超时或根本没有响应。
【讨论】:
我在我的应用程序中使用这种方式:
public static boolean isConnect(Activity activity) {
boolean flag = false;
ConnectivityManager cwjManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cwjManager.getActiveNetworkInfo() != null)
flag = cwjManager.getActiveNetworkInfo().isAvailable();
return flag;
}
当然,你还需要安卓权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
【讨论】: