我有两个任务在 doInBackground() 中运行。一项任务是从站点读取数据,另一项任务是从 Url 解析 xml 文件并在 imageview 中设置图像。但是我想将这两个任务分开意味着一旦从站点读取完成,它应该在 textview 中设置文本。之后应该开始 xml 解析。那我该怎么办?
这是我的代码:
private class DownloadWebPageTask extends AsyncTask<String, Void, ArrayList<String>>
{
ProgressBar progressBar;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = (ProgressBar)findViewById(R.id.showLoading);
progressBar.bringToFront();
}
@Override
protected ArrayList<String> doInBackground(String... arg0)
{
String xml = null;
ArrayList<String> lyricArtistArray = new ArrayList<String>();
//get lyrics - First task
lyricsArray = SearchHelper.findLyrics(arg0[0],arg0[1]);
lyricArtistArray.add(lyricsArray);
//get image - Second task
artistNameGlobal = arg0[1].toString();
try
{
XMLParser parser= new XMLParser();
String img;
String t = arg0[1].replace(" ","%20");
String url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+t+"&api_key=mykey";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName("artist");
for(int i=0;i<1;i++)
{
Element e = (Element)nl.item(i);
img = parser.getValue(e,"image");
System.out.print(img);
ImageView imageArtist = (ImageView) findViewById(R.id.artistImageView);
imageArtist.setImageBitmap(LoadImageFromURL(img));
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return lyricArtistArray;
}
@Override
protected void onPostExecute(ArrayList<String> lyricArtistArray)
{
progressBar.setVisibility(View.GONE);
tvMain.setTextSize(fontSize);
tvMain.setTextColor(FontColor);
if(!FontStyle.equals("None"))
{
String s = FontStyle.concat(".ttf");
String s1 = "fonts/"+s;
Typeface tf=Typeface.createFromAsset(getAssets(),s1);
tvMain.setTypeface(tf);
}
tvMain.setText(Html.fromHtml(lyricArtistArray.get(0).toString()));
tvMain.setMovementMethod(new ScrollingMovementMethod());
tvMain.setSelected(true);
}
}
我应该如何处理这两个任务?请建议我一些解决方案,以便花费最少的时间。请尽快回复我。提前谢谢。