我可能有一个愚蠢/奇怪的问题
我是 android 和 java 的新手,我需要一些建议来了解 android 的方法以及如何使用它们
我有一个看起来像这样的主要活动类
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”的类中定时器代码写在主类中
我的问题是我应该把我现在在主类中的定时器代码放在一个单独的类中,例如“定时器类”
然后从主类调用它,就像我为服务所做的那样
还是像现在一样可以
并且因为 xml 在 Internet 服务器上,我应该使用 asynctask 吗?
我是否正确理解异步任务只运行一次所以如果我使用异步任务我必须将它与计时器结合使用以保持 UI 更新
谢谢
ps 是与“类”相同的“线程”