我正处于异常
之下android.os.NetworkOnMainThreadException
因为我没有使用异步任务来进行特定的网络操作。我搜索过这个,但它让我很困惑。有人可以使用异步任务和特定功能吗?
以下是我使用的两个功能:
1) isNetworkAvailable()
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
2) hasInternetAccess(Boolean showMessage)
当我想要显示吐司时,我调用此功能,将参数设置为 true 。
public boolean hasInternetAccess(Boolean showMessage) {
if (isNetworkAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.w("connection", "Error checking internet connection", e);
}
} else {
if(showMessage) // If i want to show the toast, it's true
showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
}
return false;
}
答案 0 :(得分:1)
这是通过创建扩展AsyncTask的内部类来使用AsyncTask的方法。
private class NetworkInAsync extends AsyncTask<String, Void, Boolean> {
private Context context;
private Activity activity;
NetworkInAsync(Activity activity) {
this.context = activity.getApplicationContext();
this.activity = activity;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(Boolean result) {
// Do something with the result here
}
@Override
protected Boolean doInBackground(String... params) {
if (isNetworkAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.w("connection", "Error checking internet connection", e);
}
} else {
if(showMessage) // If i want to show the toast, it's true
showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
}
return false;
}
}
您可以按如下方式执行AsyncTask
new NetworkInAsync(this).execute();
我仍然建议您浏览文档here,以了解AsyncTask在Android中的工作原理。
答案 1 :(得分:0)
从AsyncTask
的{{1}}方法
致电doInBackground
test();
您可以在拨打电话之前检查网络连接,但是如何在TimeOut异常中捕获异常。所以我不认为,在打电话之前,你有很多好处来检查连接性。