How to run a function background in android?

拟墨画扇 提交于 2019-12-07 13:28:27

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){
    }
  }

You could use an AsyncTask to carry out your activity in background.

Here is a good tutorial.

you need to explore the doInBackground function of AsyncTask class.

check out the documentation and this example.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!