[英]How to Handle Internet Connection when Requesting Data to RestAPI Android
I have asynctask
for requesting JSON file from RestAPI, the problem is before webservice send JSON data, my connection have been lost, and get error because of that. 我有
asynctask
用于从RestAPI请求JSON文件的asynctask,问题是在Web服务发送JSON数据之前,我的连接已丢失,并因此而出错。 I already have ConnectivityManager
to check if connection establish i can run the asynctask
for requesting JSON. 我已经有
ConnectivityManager
来检查连接是否建立,我可以运行asynctask
来请求JSON。 How to handle when asynctask
is already running? 当
asynctask
已在运行时,如何处理?
This is my ConnectivityManager
function: 这是我的
ConnectivityManager
函数:
public bool isOnline()
{
ConnectivityManager cm = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo activeConnection = cm.ActiveNetworkInfo;
return activeConnection != null && activeConnection.IsConnected;
}
I'm using Visual Studio 2015 and Xamarin to build Android App. 我正在使用Visual Studio 2015和Xamarin来构建Android应用程序。
Thanks in advance 提前致谢
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Net Utils for android
*/
public class NetUtils {
/**
* @param context the context you're checking connectivity for
* @return true if the application can access the internet
*/
public static boolean hasConnectivity(Context context, boolean roamingOK) {
boolean hasConnectivity = true;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
hasConnectivity = info != null && (info.isConnected() || (roamingOK && info.isRoaming()));
return hasConnectivity;
}
}
also add permission on manifest 同时在清单上添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.