简体   繁体   中英

Android same method called twice

I have a method that runs when the app is opened. It is called from onCreate. But I also call it from onResume. The problem I have is that at the moment it is running twice when the app opens. Is there a way to stop this or a better way to implement what I am trying to achieve?

Thanks

When an activity starts, onCreate() is called first and then onResume() is called,if you want it to be called only once, remove the call in onCreate() .

calling the method in onResume() will ensure that the method is called when the activity regains focus, like after back press etc..

Why not to use it only in onResume()? It IS called after onCreate anyway.

viz. http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Activity lifecycle needed steps:

Want to Start the Activity?

Activity Starts => onCreate() => onStart() => onResume() => Activity is running

Want to shut it down?

Running => onPause() => onStop() =>onDestroy() => Activity is finally shut down.

I recomend you to read this article of the official documentation: Activity

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