简体   繁体   中英

Should I get instances of classes in onResume() or onCreate()

My intuition says to do it once in onCreate() , but I am not sure if there is some advantage to having a fresh instance each time. What's the best practice here?

We need some more context to give you a straight answer. Both methods might be called multiple times depending on what the user is doing.

I suggest defaulting your object instances as null, and inside onCreate() and/or onResume() , initialize it only if it is null.

if(objectInstance == null)
{
    objectInstance = new MyObject();
}

You should not re instantiate an object that you already have unless you have a reason for it! recreating objects just gets more memory and produces more garbage for the GC that is bad for efficiency!

So initialize needed objects in onCreate()

Like Hojjat points out you should not re instantiate objects, you must create again the objects if they are not currently present,

if(myObject == null){
    myObject = new ObjectFoo();
}

but if you are using a service maybe that will require the initialization:

class A extends Activity{
    public ServiceClass mService = null; // service objecct
    public void onCreate(){
        mService = new ServiceClass();
    }

    public void onResume(){
        mService.methodA();
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM