所以,我一直在为客户创建和应用程序并进入网络部分。我目前正在从清单中删除 targetSDK 标记,所以我没有得到 MainThreadException。我已经看到人们和文档说我不应该在主线程上进行网络操作,因为它更慢......
问题:我在哪里以及如何进行网络操作而不在主线程上进行?这是代码:
public static class MagFragment extends Fragment {
public static final String ARG_MAGAZINE_NUMBER = "magazine_number";
public MagFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int i = getArguments().getInt(ARG_MAGAZINE_NUMBER);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
if(i != 0){
rootView = inflater.inflate(R.layout.fragment_magazine, container, false);
TextView magText = (TextView) rootView.findViewById(R.id.textViewMag);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://csddata.site11.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
InputStream inputstream = httpEntity.getContent();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream,"iso-8859-1"),8);
magText.setText(reader.readLine());
}catch (Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String magazine = getResources().getStringArray(R.array.magazine_array)[i];
Log.d("MagFragment", "MagNumber" + i);
getActivity().setTitle(magazine);
return rootView;
}
}