- 消息你应该总是使用
AsyncTask
在安卓
- 执行网络操作 因为任何需要更多时间来加载到UI会导致
"Unresponsive of the android application"
(ANR)
样品::
public class FrgLatein extends Fragment {
//New-Instance
public static FrgLatein newInstance(){
Log.d("FrgLatein", "newInstance");
FrgLatein fragment = new FrgLatein();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FrgLatein", "onCreateView");
View view=inflater.inflate(R.layout.frg_latein, container, false);
setHasOptionsMenu(true);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("FrgLatein", "onActivityCreated");
super.onActivityCreated(savedInstanceState);
}
@Override
public void onStart() {
Log.d("FrgLatein", "onStart");
super.onStart();
new LongOperation1().execute("");
}
private class LongOperation1 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// Do the Web service long run here
try {
String url = URL_HERE;
HttpGet httpget = new HttpGet (url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
text = Client.execute(httpget, responseHandler);
}
catch(Exception ex) {
text = ex.getLocalizedMessage();
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
// Do the UI-task here
}
@Override
protected void onPreExecute() {
// Do the UI-task here
}
@Override
protected void onProgressUpdate(Void... values) {
// Do the UI-task here which has to be done during backgroung tasks are running like a downloading process
}
}
}
请打破悬念,而例外的是... – nobalG
这很容易。这个异常可能是'NetworkOnMainThreadException'或者叫做什么。顺便说一句:尽量避免catch-alls('catch(Exception ex)') – stealthjong