Ubuntu TechHive
building-your-first-android-app-in-java.md
Building your first Android App in Java
article.detail

Building your first Android App in Java

reading.progress 28 min read

Description of Building your first Android App in Java

Building your first Android App in Java

ll smartphone sales worldwide in Q4 2023.

[FR]
Le système d'exploitation Android possède la plus grande base installée parmi les plateformes mobiles à travers le monde. BACKLINKO

  • DĂ©but 2024, Android dĂ©tient une part de marchĂ© mondiale de 70,69 %.
  • Aux États-Unis, les iPhones ont une part de marchĂ© de 60,77 %.
  • Plus de 3 milliards d'appareils Android sont actuellement actifs.
  • Les smartphones Android ont reprĂ©sentĂ© 56 % des ventes mondiales de smartphones au quatrième trimestre 2023.

History

  • Android was created by the Open Handset Alliance, which is led by Google.
  • On August 18, 2008, the Android 0.9 SDK beta was released
  • On December 5, 2008, Google announced the first Android Dev Phone.

[FR]
Historique

  • Android a Ă©tĂ© créé par la Open Handset Alliance, dirigĂ©e par Google.
  • Le 18 aoĂ»t 2008, la version bĂŞta du SDK Android 0.9 a Ă©tĂ© lancĂ©e.
  • Le 5 dĂ©cembre 2008, Google a annoncĂ© le premier tĂ©lĂ©phone pour dĂ©veloppeurs Android (Android Dev Phone).

Android OS components:

Linux Kernel: The core of the Android operating system is based on the Linux kernel, which is written in C and C++ Native Libraries: Many core components and services of the Android system are built using native code written in C and C++. These native libraries provide essential functionalities and are exposed to developers through Java APIs. Android Runtime (ART): The Android Runtime (ART) and its predecessor, Dalvik, are responsible for running Android applications. These runtimes execute bytecode compiled from Java source code or Kotlin Java API Framework: The higher-level APIs and application framework are written in Java. This allows developers to write Android applications using Java, which are then compiled into bytecode and run on the Android Runtime

[FR] \\

Linix Kernel : Le cœur du système d'exploitation Android est basé sur le noyau Linux, écrit en C et C++. Bibliothèques natives : De nombreux composants et services essentiels d'Android sont construits avec du code natif en C et C++, accessibles via des API Java. Android Runtime (ART) : ART, et son prédécesseur Dalvik, exécutent les applications Android en bytecode, compilé à partir de code Java ou Kotlin. Framework d'API Java : Les API et frameworks de plus haut niveau sont écrits en Java, permettant aux développeurs d'écrire des applications exécutées sur l'Android Runtime.

Android operating system is open source.

  • Freely available for possible modification and redistribution.
  • CyanogenMod is one of the popular open source Android redistributions.
  • Limitations: Closed-source Google applications such as Google Play and google GPS navigation.

[FR]
Le système d'exploitation Android est open source.

  • Disponible librement pour modifications et redistribution.
  • CyanogenMod est l'une des redistributions open source populaires d'Android.
  • Limites : Applications propriĂ©taires de Google comme Google Play et la navigation GPS de Google restent fermĂ©es.

Role of Java in Android development. Java Java is one of the preferred langugages for android developments and that is because:

  • JAVA is an Object-Oriented Programming (OOP): Java’s OOP principles make it easier to manage and maintain complex codebases. This modular approach allows developers to create reusable and scalable code.
  • Platform Independence: Java’s “Write Once, Run Anywhere” capability ensures that code written in Java can run on any device that supports the Java Virtual Machine (JVM). This cross-platform compatibility is a significant advantage for Android development
  • Robust and Secure: Java is known for its robustness and security features. It includes strong memory management, exception handling, and a comprehensive security framework, making it ideal for developing secure Android applications
  • Extensive Libraries and Tools: Java offers a rich set of libraries and development tools that simplify the development process. These libraries provide pre-built functionalities, reducing the need to write code from scratch
  • Performance: Java’s performance is optimized for Android development. The Just-In-Time (JIT) compiler and efficient garbage collection contribute to the smooth performance of Android applications1.
  • Existing Developer Base: Java was already a widely-used and well-known programming language with a large community of developers. This meant that there was a ready pool of talent familiar with Java, making it easier for Google to attract developers to the Android platform2.
  • Sun Microsystems’ Support: At the time, Sun Microsystems, the original creator of Java, actively encouraged the adoption of Java and had an agreement with Google to use Java for Android. This support was a significant factor in Google’s decision

[FR]
- JAVA est un langage de programmation orienté objet (OOP) : Les principes OOP de Java facilitent la gestion et la maintenance des bases de code complexes, permettant un code modulaire, réutilisable et évolutif. - Indépendance de la plateforme : La capacité "Write Once, Run Anywhere" de Java garantit que le code peut s'exécuter sur tout appareil prenant en charge la JVM, offrant une compatibilité multiplateforme avantageuse pour le développement Android. - Robuste et sécurisé : Java est réputé pour sa gestion mémoire, sa gestion des exceptions et son cadre de sécurité complet, idéal pour des applications Android sécurisées. - Bibliothèques et outils étendus : Java propose un ensemble riche de bibliothèques et d'outils facilitant le développement. - Performance : Java est optimisé pour Android grâce au compilateur JIT et à une gestion efficace de la mémoire, assurant une performance fluide des applications. - Base de développeurs existante : Java était déjà un langage populaire, avec une grande communauté, facilitant ainsi l'adoption par les développeurs pour la plateforme Android. - Soutien de Sun Microsystems : À l'époque, Sun Microsystems, créateur de Java, encourageait activement son adoption et avait un accord avec Google pour son utilisation dans Android.

Prerequisites for Android App Development

Basic Programming Knowledge:

  • Familiarity with programming concepts and languages such as Java or Kotlin.
  • Understanding of object-oriented programming (OOP) principles.
  • Basic understanding of XML (eXtensible Markup Language) for designing user interfaces in Android

[FR] \\

  • FamiliaritĂ© avec des concepts de programmation et des langages tels que Java ou Kotlin.
  • ComprĂ©hension des principes de la programmation orientĂ©e objet (OOP).
  • ComprĂ©hension basique du XML (eXtensible Markup Language) pour la conception d'interfaces utilisateur dans Android.
graph TD
    A[User] -->|User interacting with View| B[View]
    B -->|Request Process| C[Controller]
    C -->|Asking Model to provide Data| D[Model]
    D -->|Asking Data from DB| E[(Database)]
    E -->|Response from DB| D
    D -->|Returning the Data| C
    C -->|Rendering the content| B
    B -.-> A

    %% Color and style enhancements
    style A fill:#f9c1c1,stroke:#333,stroke-width:2px
    style B fill:#ffff99,stroke:#333,stroke-width:2px
    style C fill:#d9f9a1,stroke:#333,stroke-width:2px
    style D fill:#a1c1f9,stroke:#333,stroke-width:2px
    style E fill:#ff9999,stroke:#333,stroke-width:2px

    %% Separating User and Database
    subgraph User Interaction
        A
        B
    end

    subgraph Backend
        C
        D
        E
    end

Development Environment:

This is a nice youtube video tutorial for installing Android Studio: Android Studio + SDK Configs

  • Android Studio: Download and install the latest version of Android Studio, the official Integrated Development Environment (IDE) for Android development.
  • Android SDK: when prompted, install the Android Software development Kit (SDK). Android SDK is a collection of libraries and Software Development tools that are essential for Developing Android Applications. Whenever Google releases a new version or update of Android Software, a corresponding SDK also releases with it. You may also install newer versions by doing these steps:

    • Open Android Studio -> Click on Tools -> Click on SDK Manager and install any version of your choice.
  • Setting up an Emulator:

    • Click on Tools -> Device Manager -> Add new Device -> create virtual device
    • Follow the prompts.
  • Using a Physical Device: Alternatively, you can use a physical Android device for testing by enabling Developer Options and USB Debugging.

    • Click on settings -> About …
    • Rapidly tap Build number seven times in a row (A popup message will appear when you are close to enabling the mode)
    • Go to developer options and enbale USB Debugging.

[FR] \\

C'est un excellent tutoriel vidéo YouTube pour installer Android Studio : Android Studio + Configurations SDK

  • Android Studio : TĂ©lĂ©chargez et installez la dernière version d'Android Studio, l'IDE officiel pour le dĂ©veloppement Android.
  • Android SDK : Lorsque vous y ĂŞtes invitĂ©, installez le kit de dĂ©veloppement logiciel Android (SDK). Vous pouvez installer des versions plus rĂ©centes en suivant ces Ă©tapes :

    • Ouvrez Android Studio -> Cliquez sur Outils -> SDK Manager et installez la version souhaitĂ©e.
  • Configurer un Ă©mulateur :

    • Cliquez sur Outils -> Gestionnaire de pĂ©riphĂ©riques -> Ajouter un nouvel appareil -> crĂ©er un appareil virtuel.
  • Utiliser un appareil physique : Activez les options de dĂ©veloppeur et le dĂ©bogage USB.

Getting Started

Understanding Android Project Structure

  • App Module: The main module containing your app’s source code, resources, and app-level settings like the AndroidManifest.xml and build.gradle files. When you create a new project, the default app module is named “app”
  • Library Module: (Project View Mode): External Libraries Contains reusable code that can be used as a dependency in other app modules or projects. It generates an Android Archive (AAR) file
  • Project Files:

    • build.gradle: The root build file containing plugin declarations and common configurations for all subprojects.
    • settings.gradle: Contains global build information, including project names and subprojects to include.
    • local.properties: Contains properties related to the local machine, such as the Android SDK location (excluded from source control), you may also add your api keys here.
  • Directory Structure:

    • src/main/AndroidManifest.xml: Declares essential information about your app, including components and permissions.
    • src/main/java: Contains the Java or Kotlin source code for your app.
    • src/main/res: Contains resource files like layouts, drawables, and strings.

[FR] \\

Comprendre la structure du projet Android

  • Module App : Le module principal contenant le code source, les ressources et les paramètres de l'application (AndroidManifest.xml, build.gradle).
  • Module Bibliothèque : (Mode Vue Projet) Contient du code rĂ©utilisable sous forme de fichier AAR.
  • Fichiers du Projet :

    • build.gradle, settings.gradle, local.properties.
  • Structure des Dossiers :

    • src/main/AndroidManifest.xml
    • src/main/java
    • src/main/res

For more detailed information, please refer to the original documentation.

Understanding Android Components

  • Activities: Activities represent a single screen with a user interface. They are the entry point for interacting with the user. Fragments have their own lifecycle, which is closely tied to the lifecycle of the host activity. This allows for better control over the UI components and their state management.

[FR] \\

Comprendre les composants Android

  • ActivitĂ©s : Les activitĂ©s reprĂ©sentent une seule interface utilisateur et sont le point d'entrĂ©e pour interagir avec l'utilisateur. Les fragments ont leur propre cycle de vie, Ă©troitement liĂ© Ă  celui de l'activitĂ© hĂ´te, ce qui permet un meilleur contrĂ´le des composants UI et de leur gestion d'Ă©tat.

For more details, you can refer to the original documentation or a guide on Android architecture.

public class MainActivity extends AppCompatActivity {
  // Code for the activity
}
Fragments: Fragments introduce modularity into your app’s UI by letting you divide the UI into discrete chunks. This makes it easier to manage and reuse components across different parts of your app.
  • Fragments: Fragments introduce modularity into your app’s UI by letting you divide the UI into discrete chunks. This makes it easier to manage and reuse components across different parts of your app.

[FR] \\

  • Fragments: : Les fragments introduisent la modularitĂ© dans l'interface utilisateur de votre application en vous permettant de diviser l'interface en blocs distincts. Cela facilite la gestion et la rĂ©utilisation des composants dans diffĂ©rentes parties de l'application.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, new ExampleFragment());
transaction.addToBackStack(null);
transaction.commit();
  • Services: Services run in the background to perform long-running operations or to perform work for remote processes. Example: A music player app might use a service to play music in the background while the user is in a different app

[FR] \\

  • Services : Les services s'exĂ©cutent en arrière-plan pour effectuer des opĂ©rations de longue durĂ©e ou des tâches pour des processus distants. Exemple : Une application de lecteur de musique peut utiliser un service pour jouer de la musique en arrière-plan pendant que l'utilisateur utilise une autre application.
public class MusicService extends Service {
  // Code for the service
}
  • Content Providers: Content providers manage access to a structured set of data. They encapsulate the data and provide mechanisms for defining data security. In short, a Content Provider is Andoid's way of allowing apps to share their data with other apps Example: An app that stores user contacts might use a content provider to manage contact data.

[FR] \\

  • Content Providers : Les content providers gèrent l'accès Ă  un ensemble structurĂ© de donnĂ©es. Ils encapsulent les donnĂ©es et fournissent des mĂ©canismes pour dĂ©finir la sĂ©curitĂ© des donnĂ©es. En rĂ©sumĂ©, un Content Provider permet aux applications Android de partager leurs donnĂ©es avec d'autres applications. Exemple : Une application qui stocke les contacts d'un utilisateur peut utiliser un content provider pour gĂ©rer ces donnĂ©es de contact.
public class ContactsProvider extends ContentProvider {
  // Code for the provider
}
  • Broadcast Receivers: Broadcast receivers respond to system-wide broadcast announcements. They enable the app to listen for specific broadcast messages from the system or other apps. Example: An app might use a broadcast receiver to detect when the device low battery.

[FR] \\

  • Broadcast Receivers : Les broadcast receivers rĂ©agissent aux annonces système globales. Ils permettent Ă  l'application d'Ă©couter des messages spĂ©cifiques du système ou d'autres applications. Exemple : Une application peut utiliser un broadcast receiver pour dĂ©tecter lorsque la batterie de l'appareil est faible.
batteryLevel = new BatteryLevel();
mContext.registerReceiver(batteryLevel, new IntentFilter(Intent.ACTION_BATTERY_LOW));
  • Intents: Intents are messaging objects used to request an action from another app component. They facilitate communication between different components. Example: An intent can be used to start a new activity or to send a broadcast.

[FR] \\

  • Intents : Les intents sont des objets de messagerie utilisĂ©s pour demander une action Ă  un autre composant de l'application. Ils facilitent la communication entre diffĂ©rents composants. Exemple : Un intent peut ĂŞtre utilisĂ© pour dĂ©marrer une nouvelle activitĂ© ou envoyer une diffusion (broadcast).
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
  • Layouts: Layouts are containers that hold and arrange views in a specific manner. They define the structure and positioning of the UI components Common Layouts:

    • LinearLayout: Arranges views in a single row or column.
    • RelativeLayout: Positions views relative to each other or the parent container.
    • ConstraintLayout: A flexible layout that allows you to create complex layouts with a flat view hierarchy.
    • FrameLayout: A simple layout that stacks views on top of each other.
    • GridLayout: Arranges views in a grid format.
    • Layout Editor: Use the Layout Editor in Android Studio to visually design your UI. Drag and drop UI components from the palette, and configure their properties using the attributes panel
  • Views: Views are the basic building blocks of an Android user interface. They represent the UI components that users interact with, such as buttons, text fields, images, and more1. Common Views:

    • TextView: Displays text to the user.
    • Button: A clickable button.
    • ImageView: Displays an image.
    • EditText: A text field for user input.
    • ListViews
    • RecyclerView: A flexible view for displaying large data sets in a scrollable list.
    • ListViews and Adapters: ListViews are android elements used to display items in a list. Adapters are used to bind an array of data to a ListView. It is a simple adapter that can handle a single list of items.

[FR] \\

  • Layouts : Les layouts sont des conteneurs qui organisent et disposent les vues dans une interface utilisateur.

    • LinearLayout : Dispose les vues en une seule ligne ou colonne.
    • RelativeLayout : Positionne les vues les unes par rapport aux autres ou au conteneur parent.
    • ConstraintLayout : Permet des mises en page complexes.
    • FrameLayout : Empile les vues les unes sur les autres.
    • GridLayout : Organise les vues en grille.
  • Views : Composants de base de l'interface utilisateur, comme
  • TextView : Affiche du texte Ă  l'utilisateur.
  • Button : Un bouton cliquable.
  • ImageView : Affiche une image.
  • EditText : Un champ de texte pour la saisie de l'utilisateur.
  • ListView : Affiche une liste d'Ă©lĂ©ments.
  • RecyclerView : Vue flexible pour afficher de grandes sĂ©ries de donnĂ©es dans une liste dĂ©filante.
  • ListViews et Adapters : ListViews sont utilisĂ©s pour afficher des listes, et les Adapters lient les donnĂ©es Ă  cette liste.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataArray);
listView.setAdapter(adapter);
public class CustomAdapter extends BaseAdapter {
  // Implementation of custom adapter
}

Basic UI design

  • XML Layouts: Designing with XML.

    
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello, World!" />
    
    
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Click Me" />
    
  • Introduction to Material Design principles: Material Design is a design system developed by Google to create high-quality digital experiences across various platforms, including Android, iOS, Flutter, and the web. It is inspired by the physical world and its textures, incorporating principles from print design to create a cohesive and immersive user experience12. Using Material design

    • Add Material Components to your project: Open your build.gradle file and add the following dependency:

[FR]
Introduction aux principes du Material Design : Material Design est un système de conception développé par Google pour créer des expériences numériques de haute qualité sur Android, iOS, Flutter et le web. Inspiré du monde physique et des textures, il incorpore des principes du design imprimé pour offrir une expérience utilisateur immersive.

  • Ajouter des composants Material Ă  votre projet : Ouvrez votre fichier `build.gradle` et ajoutez la dĂ©pendance suivante :
implementation 'com.google.android.material:material:1.4.0'

Update your app theme:

 name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    
     name="colorPrimary">@color/primary
     name="colorPrimaryVariant">@color/primaryVariant
     name="colorOnPrimary">@color/onPrimary
     name="colorSecondary">@color/secondary

Use Material Components in your layouts. Example material button


    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Material Button" />

Handling User inputs: Example Button.

XML


    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Material Button" />

JAVA

MaterialButton button = findViewById(R.id.materialButton);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Handle button click
    }
});

Working with Data

  • Managing data using SharedPreferences: SharedPreferences is a simple way to store small amounts of data as key-value pairs. [FR] \\
  • GĂ©rer les donnĂ©es avec SharedPreferences : SharedPreferences est un moyen simple de stocker de petites quantitĂ©s de donnĂ©es sous forme de paires clĂ©-valeur. Cela permet de sauvegarder des prĂ©fĂ©rences d'utilisateur ou des paramètres de l'application de manière persistante.

    Get a SharedPreferences instance: - Obtenir une instance de SharedPreferences

    SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);

    Save data to SharedPreferences: - Enregistrer des données dans SharedPreferences

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("key", "value");
    editor.apply();

    Retrieve data from SharedPreferences: - Récupérer des données depuis SharedPreferences :

    String value = sharedPreferences.getString("key", "default_value");
  • Basics of Networking in Android (Using REST APIs) - Principes de base du rĂ©seau sous Android (utilisation des API REST)
  • Android permission Intro

    <uses-permission android:name="android.permission.INTERNET" />
  • Retrofit
  • OkHttp3 Using OkHttp3: add the OkHttp3 dependency to your build.gradle file:
  implementation 'com.squareup.okhttp3:okhttp:4.9.1'

Make Network Requests You can make both synchronous and asynchronous network requests using OkHttp3. Here’s an example of how to perform a GET request:

synchronous Get Request

  OkHttpClient client = new OkHttpClient();
  Request request = new Request.Builder()
      .url("https://api.example.com/data")
      .build();

  try (Response response = client.newCall(request).execute()) {
      if (response.isSuccessful()) {
          String responseData = response.body().string();
          // Handle the response
      }
  } catch (IOException e) {
      e.printStackTrace();
  }

asynchronous Get Request

  OkHttpClient client = new OkHttpClient();
  Request request = new Request.Builder()
      .url("https://api.example.com/data")
      .build();

  client.newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
          e.printStackTrace();
      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
          if (response.isSuccessful()) {
              String responseData = response.body().string();
              // Handle the response
          }
      }
  });

Understanding Android Activity Lifecycle

  • onCreate()

Called when: The activity is first created. Purpose: Initialize the activity. This is where you should perform one-time setup procedures, such as creating the UI, initializing variables, and binding data to lists. Example:

[FR]
Appelée lorsque : L'activité est créée pour la première fois. But : Initialiser l'activité. C'est ici que vous devez effectuer les procédures de configuration uniques, telles que la création de l'interface utilisateur, l'initialisation des variables, et le binding des données aux listes. Exemple :

@Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     // Initialize components here
 }
  • onStart()

Called when: The activity becomes visible to the user. Purpose: Prepare the activity to enter the foreground and become interactive. Example:

[FR]
Appelée lorsque : L'activité devient visible pour l'utilisateur. But : Préparer l'activité à entrer au premier plan et à devenir interactive. Exemple :

 @Override
 protected void onStart() {
     super.onStart();
     // Perform tasks to make the activity visible
 }
  • onResume()

Called when: The activity starts interacting with the user. Purpose: Resume any paused UI updates, animations, or other ongoing actions.

[FR]
Appelée lorsque : L'activité commence à interagir avec l'utilisateur. But : Reprendre les mises à jour de l'interface utilisateur en pause, les animations ou d'autres actions en cours.

@Override
protected void onResume() {
        super.onResume();
        // Resume interactions with the user
}
  • onDestroy()

Called when: The activity is about to be destroyed. Purpose: Clean up any resources, such as threads or database connections, that need to be released.

[FR]
Appelée lorsque : L'activité est sur le point d'être détruite. But : Nettoyer toutes les ressources, telles que les threads ou les connexions à la base de données, qui doivent être libérées.

@Override
protected void onDestroy() {
        super.onDestroy();
        // Clean up resources
}

Introduction to Java for Android

Basic Java concepts relevant to Android development (OOP, classes, methods)

  • Object-Oriented Programming (OOP) OOP is a programming paradigm based on the concept of “objects,” which can contain data and code. The main principles of OOP are:

    • Encapsulation: Bundling data (fields) and methods (functions) that operate on the data into a single unit, or class.
    • Inheritance: Creating new classes based on existing ones, allowing for code reuse and the creation of a hierarchical relationship between classes.
    • Polymorphism: Allowing objects to be treated as instances of their parent class rather than their actual class, enabling one interface to be used for a general class of actions.
    • Abstraction: Hiding the complex implementation details and showing only the necessary features of an object.
  • Classes and Objects

Class: A blueprint for creating objects. It defines a datatype by bundling data and methods that work on the data into one single unit.

[FR] \\

Concepts de base de Java pertinents pour le développement Android (POO, classes, méthodes)

  • Programmation orientĂ©e objet (POO) : Un paradigme basĂ© sur les « objets », qui contiennent des donnĂ©es et du code. Les principaux principes de la POO sont :

    • Encapsulation : Regrouper les donnĂ©es et mĂ©thodes dans une seule unitĂ© (classe).
    • HĂ©ritage : CrĂ©er de nouvelles classes Ă  partir de classes existantes.
    • Polymorphisme : Permettre aux objets d'ĂŞtre traitĂ©s comme des instances de leur classe parente.
    • Abstraction : Cacher les dĂ©tails complexes et montrer uniquement les fonctionnalitĂ©s essentielles.
  • Classes et Objets Classe : Un modèle pour crĂ©er des objets, dĂ©finissant des donnĂ©es et des mĂ©thodes.
public class Car {
        // Fields
        private String color;
        private String model;

        // Constructor
        public Car(String color, String model) {
            this.color = color;
            this.model = model;
        }

        // Methods
        public void displayInfo() {
            System.out.println("Car model: " + model + ", Color: " + color);
        }
    }

Object: An instance of a class. It is created using the new keyword

[FR]
Objet : Une instance d'une classe. Il est créé en utilisant le mot-clé `new`.

    Car myCar = new Car("Red", "Toyota");
    myCar.displayInfo(); // Output: Car model: Toyota, Color: Red

Methods: Methods are functions defined within a class that describe the behaviors of the objects created from the class.

[FR]
Méthodes : Les méthodes sont des fonctions définies à l'intérieur d'une classe qui décrivent les comportements des objets créés à partir de cette classe.

      public class Calculator {
          // Method to add two numbers
          public int add(int a, int b) {
              return a + b;
          }

          // Method to subtract two numbers
          public int subtract(int a, int b) {
              return a - b;
          }
      }
  • Relevance to Android Development
  • Activities: (Inheritance) In Android, an activity represents a single screen with a user interface. Each activity is implemented as a subclass of the Activity class.
  • XML Layouts: (Abstraction & )Define the UI elements and their properties. These layouts are linked to activities.
  • Intents: Used to start activities or communicate between components.
  • AsyncTask: (Abstraction) Helps in performing background operations and updating the UI thread.
  • Event handling in Android. Event handling in Android involves managing user interactions with the app’s UI components. Here are the key concepts and methods you need to know: Event Listeners and Handlers Event listeners are interfaces in the View class that contain callback methods. These methods are called when the user interacts with the UI component to which the listener is registered. Event handlers are the methods that handle these events. Common Event Listeners and Handlers: OnClickListener OnLongClickListener
  • What is an Interface? An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. They are used to specify a set of methods that a class must implement.

[FR]
Pertinence pour le développement Android :

  • ActivitĂ©s : (HĂ©ritage) Une activitĂ© reprĂ©sente un Ă©cran et est une sous-classe de la classe `Activity`.
  • Layouts XML :(Abstraction)* DĂ©finit les Ă©lĂ©ments UI, reliĂ©s aux activitĂ©s.
  • Intents: UtilisĂ©s pour lancer des activitĂ©s ou communiquer entre composants.
  • AsyncTask :(Abstraction) Permet d'effectuer des opĂ©rations en arrière-plan tout en mettant Ă  jour le thread UI.

Gestion des événements en Android :* Utilise des auditeurs comme `OnClickListener` pour capturer les interactions utilisateur.

Interface : Type de référence définissant un ensemble de méthodes qu'une classe doit implémenter. Creating an Interface

public interface MyInterface {
        void myMethod();
    }

Implementing an Interface A class that implements an interface must provide implementations for all the methods declared in the interface:

public class MyClass implements MyInterface {
        @Override
        public void myMethod() {
            // Implementation of myMethod
        }
    }

Common Use Cases in Android

  • Event Handling: example: OnClickListener
  • Callbacks: Interfaces are used to create callback methods. For example, you might define an interface to handle communication between a fragment and its parent activity.

[FR]
Cas d'utilisation courants dans Android :

  • Gestion des Ă©vĂ©nements : Exemple : `OnClickListener` pour capturer des clics sur des Ă©lĂ©ments de l'interface utilisateur.
  • Callbacks : Les interfaces sont utilisĂ©es pour crĂ©er des mĂ©thodes de rappel. Par exemple, une interface peut ĂŞtre dĂ©finie pour gĂ©rer la communication entre un fragment et son activitĂ© parente.

Building the Pizza Search App

  • Step-by-step walkthrough of the app's key features.
  • Using an API and AI to search for pizza.

[FR] \\

  • FonctionnalitĂ©s principales Ă©tape par Ă©tape : Un aperçu dĂ©taillĂ© des fonctionnalitĂ©s principales de l'application.
  • Utilisation d'une API et de l'IA pour rechercher des pizzas : L'application intègre une API et une intelligence artificielle pour faciliter la recherche de pizzas.

Testing and Debugging

  • Using the Android Emulator.
  • Debugging common issues

[FR] \\

  • Utilisation de l'Ă©mulateur Android : Permet de tester des applications sur un appareil virtuel sans nĂ©cessiter de matĂ©riel physique.
  • DĂ©bogage des problèmes courants : RĂ©solution des erreurs et des dysfonctionnements frĂ©quents lors du dĂ©veloppement et des tests d'applications Android.

Deploying Your App

  • Running your app on a physical device.
  • Publishing basics (introduction to Google Play Store). Youtube

    • Create a Developer Account: Sign up for a developer account on the Google Play Console.
    • Prepare Your App for Release: Build a release version of your app.
    • Store Listing: Provide details like app title, description, screenshots, and promotional graphics.
    • App Release: Choose how you want to release your app (alpha, beta, or production).
    • Content Rating: Complete the content rating questionnaire.
    • Pricing & Distribution: Set the price and distribution options.
    • App Content: Add any additional content like in-app purchases or ads.
    • App Releases: Upload the APK file and publish your app

[FR]
Exécuter votre application sur un appareil physique. Principes de base de la publication (introduction au Google Play Store).** Youtube

  • CrĂ©er un compte dĂ©veloppeur : Inscrivez-vous sur Google Play Console.
  • PrĂ©parer l'application : Construire la version de production.
  • Liste de l'application : Fournir titre, description, captures d'Ă©cran, etc.
  • Publication : Choisissez entre alpha, bĂŞta, ou production.
  • Évaluation de contenu : Remplir le questionnaire.
  • Tarification et distribution : Fixez le prix et les options de distribution.
  • Contenu de l'application : Ajoutez des achats intĂ©grĂ©s ou des publicitĂ©s.
  • Publiez : TĂ©lĂ©chargez le fichier APK et publiez.

Final App Demo

  • Demonstrating the pizza search app in action.
  • Discussing potential enhancements and next steps.

    • In App purchase: (Google Pay | Credit Cards | Orange Money | etc)
    • Clear cart
    • Allow users to complete all app actions using their voice.

[FR] \\

  • DĂ©monstration de l'application de recherche de pizza en action.
  • Discussion sur les amĂ©liorations potentielles et les prochaines Ă©tapes :

    • Achat intĂ©grĂ© : (Google Pay | Cartes de crĂ©dit | Orange Money | etc.)
    • Vider le panier.
    • Permettre aux utilisateurs d'effectuer toutes les actions de l'application avec leur voix.

Android Garbage Collection Android Garbage Collection Nice Article by Augusto Herbel

  • Introduction to Garbage Collection (GC)

    • GC is a form of automatic memory management.
    • The primary goal is to reclaim memory occupied by objects that are no longer in use.
  • Evolution of GC in Android

    • Dalvik VM: Early versions of Android used Dalvik VM, which had a simple GC mechanism.
    • ART (Android Runtime): Replaced Dalvik in Android 5.0 (Lollipop) with more efficient GC algorithms.
  • GC Algorithms

    • Mark-and-Sweep: Identifies and marks live objects, then sweeps through to reclaim memory from unmarked objects.
    • Generational GC: Divides objects into generations (young and old) to optimize GC performance.
  • GC Triggers

    • GC can be triggered by various events, such as memory allocation failures or reaching a predefined memory limit.
  • Impact on Performance

    • GC can cause pauses in application execution, leading to performance issues like jank (unresponsive UI).
    • Optimizations in ART aim to minimize these pauses and improve overall performance.
  • Best Practices for Developers

    • Minimize object creation and reuse objects when possible. Best Practice: Avoid creating unnecessary objects to reduce the workload on the garbage collector. Example: Instead of creating a new String object in a loop, use a StringBuilder to concatenate strings.

[FR]
Introduction Ă  la collecte des ordures (GC)

  • La GC est une forme de gestion automatique de la mĂ©moire.
  • Objectif principal : rĂ©cupĂ©rer la mĂ©moire occupĂ©e par des objets inutilisĂ©s.

Évolution de la GC dans Android

  • Dalvik VM : Versions Android prĂ©coces, GC simple.
  • ART (Android Runtime) : Remplace Dalvik avec des algorithmes GC plus efficaces.

Algorithmes GC

  • Mark-and-Sweep : Marque les objets vivants et libère la mĂ©moire des non-marquĂ©s.
  • GC gĂ©nĂ©rationnel : Divise les objets par gĂ©nĂ©ration pour optimiser la performance.
    // Inefficient
    for (int i = 0; i < 1000; i++) {
        String result = "Number: " + i;
    }

    // Efficient
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < 1000; i++) {
        builder.append("Number: ").append(i);
    }
    String result = builder.toString();
    // Inefficient
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    // Efficient
    Bitmap bitmap = bitmapPool.get(width, height, Bitmap.Config.ARGB_8888);

Use memory profiling tools to identify and fix memory leaks. Best Practice: Regularly use memory profiling tools to identify and fix memory leaks. Example: Use Android Studio’s Memory Profiler to monitor your app’s memory usage and detect memory leaks. View -> Tool Windows -> Profiler the select the memory usage Avoid Memory Leaks Best Practice: Ensure that objects are not unintentionally retained, leading to memory leaks. Example: Use WeakReference for objects that should not prevent garbage collection.

[FR]
Utiliser les outils de profilage de mémoire pour identifier et corriger les fuites de mémoire :

  • Bonne pratique : Utilisez rĂ©gulièrement des outils de profilage pour dĂ©tecter et rĂ©soudre les fuites de mĂ©moire.
  • Exemple : Utilisez le Memory Profiler d'Android Studio pour surveiller l'utilisation de la mĂ©moire de votre application. Chemin : View -> Tool Windows -> Profiler, puis sĂ©lectionnez Memory Usage.

Éviter les fuites de mémoire :*

  • Bonne pratique : Assurez-vous que les objets ne sont pas retenus involontairement.
  • Exemple : Utilisez WeakReference pour les objets qui ne doivent pas empĂŞcher la collecte des ordures.
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4; // Downsample by a factor of 4
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.large_image, options);

Avoid Using Static References Best Practice: Avoid using static references to prevent memory leaks. Example: Instead of using a static reference to an Activity, use a WeakReference.

[FR]
Éviter l'utilisation de références statiques : Bonne pratique : Ne pas utiliser de références statiques pour éviter les fuites de mémoire. Exemple : Au lieu d'utiliser une référence statique à une Activity, utilisez une WeakReference afin que l'activité puisse être collectée par le ramasse-miettes une fois qu'elle n'est plus nécessaire.

// Inefficient
    private static Activity activity;

    // Efficient
    private static WeakReference<Activity> activityRef;