我有以下代码,我想要做的是以编程方式检查是否有互联网连接。
由于我收到NetworkOnMainThreadException,并被建议使用 AsyncTask。
我想执行网络操作hasActiveInternetConnection(Context context)并在连接到网络时返回 true ,否则返回 false 。
如何使用 AsyncTask 执行此操作?
public class NetworkUtil extends AsyncTask<String, Void, String>{
Context context;
public NetworkUtil(Context context){
this.context = context;
}
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(context).isNetworkAvailable())
{
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
boolean url= (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException …Run Code Online (Sandbox Code Playgroud)