我正在开发一个使用Jsoup的Android应用程序。在开发早期,我"绕过"必须实现任何类型的线程,因为我只想在处理线程之前完成大部分代码。我现在正试图使用AsyncTask,但我仍然得到NetworkOnMainThreadException错误。我读了很多关于AsyncTask的教程和SO帖子,但似乎仍然可以确定问题。当我添加StrictMode…除了在使用Jsoup加载数据时出现UI锁定外,应用程序可以正常工作。如果有人能告诉我我做错了什么有关AsyncTask,我会很感激。(P.S.我知道有很多代码冗余要清理,但我想让AsyncTask工作第一)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/***This is the work around used***/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/******/
up = new TreeMap<Double, String[]>();
c1 = "example.com/1";
//instansiate textviews (6)
doc1 = doc;
c2 = "example.com/2";
//instansiate textviews (6)
doc2 = doc;
c3 = "example.com/3";
//instansiate textviews (6)
doc3 = doc;
// instansiate textviews(16)
new Download().execute(c1,c2,c3);
}
private class Download extends AsyncTask<String, Integer, String[][]> {
@Override
protected String[][] doInBackground(String... urls){
out = new String[7][3];
try {
doc = Jsoup.connect(urls[0]).data().get();
//days, times, and cs arrays created and filled
String[] out1arr = {days[0], times[0], cs[0]};
//...all 7
String[] out7arr = {days[6], times[6], cs[6]};
String[][] outarrs = {out1arr,out2arr,out3arr,out4arr,out5arr,out6arr,out7arr};
for (int i= 0; i < out.length; i++){
out[i] = outarrs[i];
}
} catch (IOException e1) {
e1.printStackTrace();
}
return (out);
}
@Override
protected void onProgressUpdate(Integer... progress){
}
@Override
protected void onPostExecute(String[][] result){
Do(/*textviews(6)*/, c1, a, outa, "example1"); //a is previously instantiated double array, outa is preiously instantiated string array
Do(/*textviews(6)*/, c2, b, outb, "example2");
Do(/*textviews(6)*/, c3, c, outc, "example3");
upc00.setText(getUpc()[0][0]);
//setText for all 16
upc32.setText(getUpc()[3][2]);
}
private void Do(TextView t, TextView u, TextView v, TextView w, TextView x, TextView y,String webpage, double[] darr, String[] sarr, String show){
t.setText(doInBackground(webpage)[0][0]);
//...all 6
y.setText(doInBackground(webpage)[1][2]);
for (int i =0; i < darr.length; i++){
darr[i] = tis[i];
up.put(darr[i], out[i]);
}
}
}
private ArrayList<String[]> getMap(){
//...
return s;
}
private String[][] getUpc(){
//...
return upc;
}
框架调用doInBackground
,您不应该自己调用它。您的代码从onPostExecute
调用,该调用由框架在UI线程上调用。所以实际上你的调用运行在UI线程上。
将抓取逻辑全部移动到doInBackgound
方法中。应该使用onPostExecute
方法将结果传递给调用者。