¿Qué evento de Android solo se llama una vez hasta que se destruye la actividad?

StackOverflow https://stackoverflow.com/questions/9027507

  •  14-11-2019
  •  | 
  •  

Pregunta

Estoy buscando una sola respuesta (pero podría estar preguntando la pregunta incorrecta)

Pregunta: ¿se llama solo algún evento una vez que se destruye una actividad hasta que se destruya una actividad?

PREGUNIO PREGUNTE porque cuando mi usuario rota el teléfono al paisaje Oncreeate y ONSTART se invocan causando una clasificación de clases.

Estoy buscando un evento en el que pudiera poner el comportamiento en que solo se ejecutaría 1x (hasta que la actividad sea asesinada)

Gracias de antemano

¿Fue útil?

Solución

If it is specific to the Activity just check your savedInstanceState parameter in the onCreate event. If it is null, run your code, if not, your code has already been run.

Example:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if(savedInstanceState == null) {
        // Run your code
    }        
}

savedInstanceState will always be null when onCreate is run for the first time, and it will be populated thereafter.

Otros consejos

You don't really specify what you're trying to do with it, so I can't guarantee this is appropriate for your use, but Application.onCreate is only called once.

If you want to eliminate the recreation of your activity on an orientationchange you can listen for configchanges in the manifest.

    <activity
            android:name=".MyActivity"
            android:configChanges="orientation" >
    </activity>

And then you can override onConfigurationChanged like so:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged( newConfig );

    LinearLayout main = (LinearLayout) findViewById( R.id.mainLayout );
    main.requestLayout();
}

to recreate the layout so that it matches the new orientation, without recreating the entire activity.

Check http://developer.android.com/guide/topics/resources/runtime-changes.html to handle configuration changes and to maintain your huge data between them...if all you need to maintain between the configuration change is just the settings,you can use the onSavedInstanceState() and onRestoreInstanceState() callbacks and the given bundles.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top