0

将目标 sdk 设置为 11 后出现蜂窝错误 android.os.NetworkOnMainThreadException。我使用以下代码忽略它。它会影响我的应用程序吗?有人可以提出任何解决这个问题的建议。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 



@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_layout);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 

        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_SONG);
        // looping through all song nodes <song>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

            // adding HashList to ArrayList
            songsList.add(map);
        }
4

1 回答 1

2

在主线程(UI 线程)上进行网络访问不是一个好习惯。如果您的目标 SDK 是 Honeycomb 或更高版本,则会在主线程上出现网络异常。尝试使用异步任务来避免这种情况。

代码 EX:

public class yourclass extends Activity{
        @Override
        public void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.uoyrlayout);
        //this is UI thread you should not do network access from here.
        new LongRunning().execute();//call to background thread to do network access
 }
    public class LongRunning extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() {
            //UI updating goes here before background thread..
        }
        @Override
        protected Void doInBackground(Void... params) {     
            //This is not the UI thread
            //do your network acces
            return null;            
        }

        @Override
        protected void onPostExecute(Void result) {
           //update your UI after background thread
        }

    }
}
于 2012-08-16T03:45:29.970 回答