问题
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);
}
回答1:
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){
}
}
回答2:
You could use an AsyncTask to carry out your activity in background.
Here is a good tutorial.
回答3:
you need to explore the doInBackground function of AsyncTask class.
check out the documentation and this example.
回答4:
You can create an Android Service for this purpose and use the Alarm Manager to invoke the service.
Here is a nice tutorial
Cheers, RJ
来源:https://stackoverflow.com/questions/11445202/how-to-run-a-function-background-in-android