In the app I'm working on, there is a background task which does some heavy work. This task needs to be executed often, and involves a computationally heavy creation of some objects. Now, I understand that it would be better not to create these objects every time the task is ran, but to keep them as static
members.
This is how I was planning to do this:
The task is a Service
, which is started in the onCreate
method of an Application
class
Once the Service
is started, the heavy objects are initialized
When the task needs to be ran, bindService
is called on the service
Is this a good way of doing this? Is there a better one?
The problem that a Service
runs on the Main thread. So your scheme will not work as you wish. I would recommend you to create separate class which will create your objects.
public class HeavyObjectsHolder {
private static volatile Object[] heavyObjects;
public static Object[] get(){
return heavyObjects;
}
public static void create(){
new Thread(new Runnable() {
@Override
public void run() {
//creation of heavy objects
heavyObjects = new Object[]{
//populating array
};
}
}).start();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.