简体   繁体   中英

onCreate not called when restarting activity after it is destroyed

When I exit my app (by pressing back or the home button) the Activity s onDestroy() method is called (where I do lots of clean up with bitmaps).

When I reopen the app, onCreate() does not get called... it goes straight to onStart() , despite the fact that the Activity was finished. This is causing a "trying to use a recycled bitmap" error.

Is there a way to ensure that onCreate() is always called after an Activity is destroyed?

EDIT: I was mistaken. onCreate() IS being called. However, I am still getting the "trying to use a recycled bitmap" error. If onCreate() is going through all of it's steps, wouldn't any recycled bitmaps be reloaded?

Your app must be doing something to forcefully ensure that onDestroy gets called, because if you look at the Activity lifecycle there's no path to get back to onStart from onDestroy that doesn't include onCreate. In reality, an Activity unwinds its initialization with reverse callbacks to the ones that bring it into the resumed state. Take a look at the official documentation here Perhaps you're calling the finish() method somewhere to force quite the Activity?

when you press the home button , the activity is not destroyed , it is just sent to background , and the method onPause() is called, and when you launch it again , the method onResume() will be executed, the method onDestroy() is executed when you press the back button or when you call the method finish() to force the activity to be destroyed , and then when you try to re launch your activity , the onCreate() will be executed.

refer this

The problem was with how I was setting the ImageView image. My original way to load an image from /res was:

    image.setImageDrawable(getResources().getDrawable(R.drawable.myImage)); //WRONG!!!!

apparently if you recycled a bitmap, the above code will not reallocate memory for the bitmap, and your program will crash when it tries to draw that ImageView.

The correct way to load a bitmap that has been recycled (or at least, the way that solved my problem) is:

    image.setImageDrawable(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.myImage))); //correct!

It still doesn't answer my question as to why, after exiting the app, and onDestroy is called, that when I re-enter the app, it is looking for a recycled bitmap. In theory the app should be starting up from scratch.

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