我有可能是愚蠢的/奇怪的問題SAXParser的計時器和的AsyncTask
我是新來的Android和Java,我需要一些建議,瞭解機器人的方法和如何使用它們
我有一個主活動類,看起來像這樣
extends Activity implements OnClickListener{
private static final String TAG = "ServicesDemo";
public String myimageURL;
private EditText Lyrics;
private ImageView AlbumPic;
private Button play, stop;
private TextView Artist, Song, Album, News, Lyric;
private UpdateTimeTask m_updateTime;
private Handler m_handler;
Parser data;
/** The delay in milliseconds between updates. */
private final int DELAY = 20000;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Artist =(TextView)findViewById(R.id.tvArtist);
Song =(TextView)findViewById(R.id.tvSongTitle);
Album =(TextView)findViewById(R.id.tvAlbum);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
Lyrics = (EditText) findViewById(R.id.tvLyrics);
News = (TextView)findViewById(R.id.tvAnouncement);
AlbumPic = (ImageView) findViewById(R.id.AlbumPic);
play.setOnClickListener(this);
stop.setOnClickListener(this);
m_updateTime = new UpdateTimeTask();
m_handler = new Handler();
m_handler.post(m_updateTime);
}
private class UpdateTimeTask implements Runnable {
public void run() {
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://www.mysite.com/AndroidTest.php");
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
data = XMLHandler.data;
for (int i = 0; i < data.getTitle().size(); i++) {
Lyrics.setText(data.getLyric().get(i));
myimageURL = data.getPic().get(i);
Song.setText("Title = "+data.getTitle().get(i));
Artist.setText("Artist = "+data.getArtist().get(i));
Album.setText("Album = "+data.getAlbum().get(i));
}
downloadFile(myimageURL);
}
Bitmap bmImg;
void downloadFile(String fileUrl) {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
AlbumPic.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m_handler.postDelayed(m_updateTime, DELAY);
AlbumPic.clearAnimation();
}
}
代碼工作正常
,你可以看到我使用計時器和服務
服務代碼是寫在一個叫做不同的類「my_service」 計時碼是寫在主類
我的問題是我應該把定時器的代碼,我現在在主類在例如「Timer類」
,然後從剛纔像我一樣的對服務
還是確定就像它的主類稱它爲一個單獨的類是現在
的d因爲xml在互聯網服務器上,我應該使用asynctask?
沒有我的理解是正確的,對的AsyncTask只運行一次,如果我使用的AsyncTask我在組合使用它與定時器保持更新UI
感謝
附:是一個「線程」相同的「類」
非常感謝您的快速回復,這讓事情變得更加清晰 – user1505173 2012-07-27 17:13:34