Вопрос

I'm new to Android and trying to figure out where to place a HTTP request in order to make it execute only once (when the Activity first become visible). onCreate is always called when returning from onActivityResult (grabbing a pic from the camera here)

Any suggestions?

Это было полезно?

Решение

Inside of the onCreate(Bundle savedInstanceState) if savedInstanceState is null then it is the first/clean start of the activity. So you can do something like this:

onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        // call HTTP request
    }

    ... the rest of onCreate()
}

Другие советы

How about setting a flag the first time you make the call within onCreate and then checking for it each time onCreate (and your code) is called. For completenes Activity lifecycle is documented here: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

OnCreate() may not be a bad place if you are either ok with having it executed always when the Activity is started or you are ready to check if this has been done already (as other answers also suggest). You could set a flag in SharedPreferences for this purpose, as this flag also survives complete shutdown of the app and restart.

Having said that: you still need to put the http request in a background thread if you ever want to make your app available on Honeycomb or even Ice Cream Sandwich, as those systems kill the app if there is any network access in the UI thread.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top