gpt4 book ai didi

android - 如何执行 AsyncTask 来检查互联网连接

转载 作者:行者123 更新时间:2023-12-02 10:07:56 25 4
gpt4 key购买 nike

我有以下代码,我想做的是以编程方式检查是否有互联网连接。
由于我收到 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 e) {

}
}


// your get/post related code..like HttpPost = new HttpPost(url);
else {
Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
}


return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}

最佳答案

使用此类来检查互联网连接...

public class CheckNetwork {
private Context context;

public CheckNetwork(Context context) {
this.context = context;
}

public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

}

那么......

将此 ASynTask 用于 httppost。

public class NetworkUtil extends AsyncTask<String, Void, String> {

private ProgressDialog dialog;

@Override
protected void onPreExecute() {
dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}

@Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) {
// your get/post related code..like HttpPost = new HttpPost(url);
} else {
// No Internet
// Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}

关于android - 如何执行 AsyncTask 来检查互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23292728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com