如何在Android中运行功能背景? [英] How to run a function background in android?
问题描述
在我的应用程序中,我有一个填充列表视图的函数.我想每5分钟定期运行一次此函数,为此我使用了以下方法.
In my application I have a function to populate listview.I want to run this function periodically on every 5 minutes.I have used following method for that.
private class RefreshThread extends Thread{
public boolean isStop = false;
public void run(){
try{
while(!isStop){
Headlines.this.runOnUiThread(new Runnable() {
public void run() {
populate_listview(); //Function to populate listview
}
});
try{ Thread.sleep(300000); } catch(Exception ex){}
}
}catch(Exception e){
}
}
}
当我使用此方法时,该函数在前台运行,因此整个应用程序都受到此影响.我想在后台运行此函数,以便列表视图更新,并且用户永远不知道该函数正在运行.
when I use this method the function runs on foreground so the entire application got affected by this.I want to run this function in background so that the listview updates and the user never knows that the function is running.
以下是填充列表视图的功能.
following is the function to populate listview.
public void populate_listview()
{
ArrayList<HashMap<String, String>> newsList = 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_HEAD);
// looping through all song nodes <song>
NodeList itemLst = doc.getElementsByTagName("item");
String MarqueeStr="";
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);
//map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
newsList.add(map);
}
推荐答案
要获得较小的性能开销,您应该做所有准备工作,包括在后台线程中填充具有适当值的HashMap
并保留在populate_listview()
方法中仅newList.add(refresh_thread.getMap());
.只需添加到RefreshThread
synchronized
方法getMap()
即可从另一个类访问此HashMap
,并添加另一个synchronized
方法prepareHashMap()
以获取准备它的代码.显然,您的HashMap
必须是RefreshThread
类的字段.然后,run()
方法将如下所示:
To get smaller performance overhead, you should do all the preparations, including populating HashMap
with proper values, in your background thread and leave in populate_listview()
method only newList.add(refresh_thread.getMap());
. Just add to RefreshThread
synchronized
method getMap()
to access this HashMap
from another class, and another synchronized
method prepareHashMap()
for the code that prepare it. Obviously, your HashMap
must be a field of RefreshThread
class. Then, the run()
method will look like this:
public void run(){
try{
while(!isStop){
prepareHashMap();
Headlines.this.runOnUiThread(new Runnable() {
public void run() {
populate_listview(); //Function to populate listview
}
});
try{ Thread.sleep(300000); } catch(Exception ex){}
}
}catch(Exception e){
}
}
这篇关于如何在Android中运行功能背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!