【发布时间】:2014-03-14 17:48:29
【问题描述】:
我是Android编程的初学者,我正在尝试向远程服务器发出Http请求,我想检查用户是否可以连接到网络,以避免我的应用程序因失败而崩溃我正在制作的 AsyncTask。
我找到了这个方法:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
但是当我尝试在 doInBackground AsyncTask 方法实现中调用它时,应用程序崩溃了:
class RemoteThread extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(IMieiDati.this);
pDialog.setMessage("Caricamento...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... strings ){
// checking whether the network is not available
// but the app crashes here
if (!isNetworkAvailable()) {
Log.d("Message", "No Network Connection. Aborting.");
}
// here I should make the request if the network is available
}
...etc, etc...
我该如何解决,例如向用户显示一条消息,例如“我们很抱歉,为了正确使用该应用程序,您应该连接到网络”或类似的内容?
谢谢!
【问题讨论】:
标签: java android android-asynctask connection