【发布时间】:2013-12-27 14:13:05
【问题描述】:
我是 android 新手,英语说得“差”。
我有一个片段,在执行 webview 之前,我必须测试 url 是否存在。
在我的第一次测试中,我得到了一个“android.os.NetworkOnMainThreadException”
所以,我使用 AsyncTask
如果 url 存在,如何在我的片段活动中进行测试??
我在 Android Studio 下测试并在调试中'doInBackground' 没有执行???
提前,非常感谢您的支持
这是我的 AsyncTask 类:
public class ExistUrl extends AsyncTask<String, Void, Boolean> {
private static final String TAG = "CheckURL";
String filename="";
public ExistUrl(String URL) {
this.filename=URL;
Log.d(TAG, "url="+ this.filename);
}
@Override
protected Boolean doInBackground(String... params) {
// validateParams(params);
Log.v("name of file",this.filename);
Boolean OK =MyUtilities.exists(params[0]);
Log.v("*********** retour exists class:", Boolean.toString(OK));
return OK;
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.i(TAG, "Background cancelled.");
}
@Override
protected void onPostExecute(Boolean result){
super.onPostExecute(result);
String message = null;
if (result)
message = "Url succeeded.";
else
message = "Url failed.";
Log.i(TAG, message); }
}}
这是 Myutilities.exists
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
我的片段活动
public class HainautFragment extends Fragment {
public HainautFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hainaut, container, false);
String Zone = "http://www.tournoi.org/tournoilive/affiche_categorie_dbf.asp?nuclb=1005&datedeb=2013/9/13&datefin=2013/9/22&IdTournoi=309569";
ConnectionDetector cd = new ConnectionDetector(getActivity());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new ExistUrl(Zone).execute();
*********************//how to test return***************************
}
return rootView;
}
【问题讨论】:
标签: android android-fragments android-asynctask