Dans le développement d'applications Android, une Activity traverse plusieurs états au cours de son cycle de vie. Ces transitions incluant : création, démarrage, exécution, pause, arrêt, destruciton et redémarrage. Ces états sont gérés par des méthodes de rappel spécifiqeus, permettant aux développeurs de contrôler le comportement de l'application à chaque phase.
Voici un exemple illustrant ces transitions avec des implémentations en Java et un fichier de mise en page XML.
Fichier EcranPrincipal.java
package com.example.exemple_activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class EcranPrincipal extends Activity {
@Override
protected void onCreate(Bundle etatSauvegarde) {
super.onCreate(etatSauvegarde);
setContentView(R.layout.ecran_principal);
Toast.makeText(this, "L'Activity a été créée, méthode onCreate() exécutée", Toast.LENGTH_LONG).show();
}
public void ouvrirInscription(View vue) {
Intent intention = new Intent(this, EcranInscription.class);
startActivity(intention);
}
@Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "L'Activity démarre, méthode onStart() exécutée", Toast.LENGTH_LONG).show();
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "L'Activity passe en état actif, méthode onResume() exécutée", Toast.LENGTH_LONG).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "L'Activity redémarre depuis l'état arrêté, méthode onRestart() exécutée", Toast.LENGTH_LONG).show();
}
@Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "L'Activity entre en pause, méthode onPause() exécutée", Toast.LENGTH_LONG).show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "L'Activity passe en état arrêté, méthode onStop() exécutée", Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "L'Activity est détruite, méthode onDestroy() exécutée", Toast.LENGTH_LONG).show();
}
}
Fichier EcranInscription.java
package com.example.exemple_activity;
import android.app.Activity;
import android.os.Bundle;
public class EcranInscription extends Activity {
@Override
protected void onCreate(Bundle etatSauvegarde) {
super.onCreate(etatSauvegarde);
setContentView(R.layout.ecran_inscription);
}
}
Fichier ecran_principal.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ecran_principal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:onClick="ouvrirInscription"
android:text="S'inscrire" />
</LinearLayout>