SlideShare a Scribd company logo
1 of 127
Pr. Zakaria Bentahar
À l’académie internationale d’aviation civile (AIAC), Casablanca, Maroc
Plan
Android : qu'est ce que c'est ? et l'Open Handset Alliance ?
Pourquoi Android ?
Positionnement par rapport à son environnement
Historique de 2005 à nos jours
Les différentes versions d’Android
Architecture du système Android
Plan
La structure d’un projet Android
Création des interfaces utilisateurs
Ressources
Activités
Intent
Persistence des données (Fichiers, SQLite)
Android
&
l'Open Handset
Alliance
Android est un système d'exploitation pour téléphone portable de
nouvelle génération développé par Google. Celui ci met à disposition
un kit de développement (SDK) basé sur le langage Java.
L'Open Handset Alliance (abrégé OHA) est un consortium de plusieurs
entreprises dont le but est de développer des normes ouvertes pour
les appareils de téléphonie mobile.
Le consortium a été créé le 5 novembre 2007 à l'initiative
de Google qui a su fédérer autour de lui 34 compagnies
Motivation
Rovio une entreprise fondé par trois étudiants d'une université de
technology en Finland a eu des revenues d'environ €75.4 million en
2011 grâce à un jeu gratuit Angry Birds, ils ont gagné plus d'un
million de dollars par mois, ceci à travers les publicités qui se lancent
automatiquement suite à chaque lancement du jeu.
Instagram est une application et un service de partage des photos
conçu par un ingénieur avec deux ans d'expériences en Gmail et un
ingénieur étudiant brézilien résidant en Californie , Facebook l'a
acheté d'eux en 1 billion $ Cach, il était uploaded au niveau de App
Store comme c'est le cas pour le reste des applications Android et il a
eu sa réputation grâce aux nombres de téléchargement.
WhatsApp est une application de messagerie instantannée réalisé par
deux anciens combattants de Yahoo, cette application qui coute juste
0.99$ après une année gratuite a réussit a faire une fortune même si
la societé n'a pas dévoilé ses revenues mais juste en la comparant
avec le nombre d'utilisation de Instagram qu'a acquiert facebook , elle
a eu plus d'utilisateurs par la suite plus de revenues.
Talking Tom Cat c'est un jeu qui étaient téléchargé plus de 400 million
fois réalisé par une societé spécialisée dans la réalisation des
applications payantes de divertissement, alors que le meilleur
nombre de téléchargement d'un logiciel comme Avast a eu juste
340987 nombre de téléchargement dans le site le plus populaire de
téléchargement télecharger.com
Positionnement par rappot à son environnement
Histoire
Versions
Versions
Pour plus de details :
http://fr.wikipedia.org/wiki/Historique_des_versions_d'
Android
Architecture
Architecture
La plate-forme Android est composée de différentes couches :
un noyau Linux qui lui confère notamment des caractéristiques
multitâches ;
des bibliothèques graphiques, multimédias ;
une machine virtuelle Java adaptée : la Dalvik Virtual Machine ;
un framework applicatif proposant des fonctionnalités de gestion
de fenêtres, de téléphonie, de gestion de contenu... ;
des applications dont un navigateur web, une gestion des contacts,
un calendrier…
Architecture
Installation
du SDK
SDK
Le SDK est un ensemble d’outils qui permet aux
développeurs et aux entreprises de créer des
applications.
http://developer.android.com/sdk/index.html
Installation process
Installation
du ADT
Configuration de Eclipse: Installation de ADT (Android Development Tools)
 crée et débogue des applications Android facile et plus
rapide
 donne accès à d'autres outils de
développement Android à l'intérieur de Eclipse.
 fournit un éditeur de code Android qui aide à écrire du
code XML valide pour le fichier de configuration et les
fichiers de ressources
 exporte le projet dans un APK signé.
ADT Plugin
http://dl-ssl.google.com/android/eclipse/
1) Installer SDK
2) Installer ADT
3) Configurer SDK dans Eclipse
Etapes de configuration de l’environnement de développement
Emulateur
CONFIGURER UN APPAREIL VIRTUEL ANDROID
AVD (Android Virtual
Devices) est un émulateur
qui joue le rôle de
smartphone
CONFIGURER UN APPAREIL VIRTUEL ANDROID
Window > Android AVD Manager
Structure du
projet
Structure du projet
Structure du projet : gen
 Contain Java files auto-generated by ADT.
 Contain the class R :
 Special static class.
 Reference the data contained in resource files.
 Contain one static inner class by resource type.
public final class R{
public static final class drawable {
public static final int
icon=0x7f020000;
}
public static final class layout {
public static final int
main=0x7f030000;
}
... //code omitted
}
Structure du projet : assets
 Contain asset files
 Quite similar to resources.
 Accessed in a classic file manipulation style
 With stream of bytes manipulation.
 Need to use AssertManager class to open them.
 Not for an usage as extensive as resources.
Structure du projet : androidManifest.xml
 Mandatory file in every Android projects.
 Contain information needed by Android to run the
application
 Package name of the application.
 List of Activities, Services, Broadcast Receivers, …
 Permissions needed by the application.
 etc…
Pourquoi
Gingerbread ?
Pourquoi 2.3 (Gingerbread) ?
Resources
Resources : Presentation
 Android externalize resources like :
 Images.
 Strings.
 User Interface description.
 …
 Easier to manage and maintain them.
 Contained inside the res folder.
Resources : Use the resources
 Resources are accessible inside the code thanks to the static
class : R.
 This class is automatically generated by ADT.
 When you add a resource inside the res folder, ADT add a
reference to it inside the R class.
 The syntax to retrieve a resource reference is :
R.resource_type.resource_name
Resources : Example
// Define the layout of an activity
setContentView(R.layout.my_screen);
// Retrieve the application name
Resources resources = getResources();
String appName = resources.getString(R.string.app_name);
public final class R{
public static final class string {
public static final int app_name=0x7f020000;
}
public static final class layout {
public static final int my_screen=0x7f030000;
}
... //code omitted
}
Resources : System Resources
 Android already includes a number of resources
 Predefined Colors.
 Predefined Strings.
 Predefined Images.
 Examples :
...
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content”
android:textColor="@android:color/darker_gray"
android:text="@string/hello”
/>
...
String cancel =
resources.getString(android.R.string.cancel);
Resources : Simple Values
 Simple values are stored in XML files inside /res/values folder.
 You can declare
 Strings
 You can use the HTML tags <b>, <i> and <u>.
 Colors
 Accept #RGB, #ARGB, #RRGGBB and #AARRGGBB format.
 Dimensions
 In pixels (px), inches (in), millimeters (mm), points (pt),
density-independent pixel (dp) or scale-independent pixel
(sp),
 Arrays
 Of Integers or Strings.
Resources : simple values’ examples
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Cyan">#00FFFF</color>
<string name="first_name">zakaria</string>
<string-array name="my_array">
<item>A string</item>
<item>Another String</item>
</string-array>
<integer-array name="my_other_array">
<item>123</item>
<item>456</item>
</integer-array>
<dimen name="my_dimension">4dp</dimen>
<dimen name="text_size">4px</dimen>
</resources>
Resources : Images
 Android accept different bitmap format for resources :
 PNG (advised by the documentation)
 JPEG
 GIF (deprecated)
 From Android 1.6, three folders :
 drawable-hdpi : resource for high-resolution screens.
 drawable-mdpi : resources for medium-resolution screens.
 drawable-ldpi : resources for low-resolution screens.
User Interfaces
User Interfaces
 A user interface is a set of graphical components like :
 Button.
 Text.
 Form field.
 Component composed of other components…
 This components are called Views.
 The last one is a special view
called ViewGroup.
User Interfaces
Views
ViewGroups
User Interfaces
 User interfaces can be defined :
 In XML, inside a layout resource file.
 Directly in the Activity code.
 We’re going to see both.
User Interfaces : XML Definition VS Java Definition
 Use XML layout to define user interfaces :
 Separate interface structure and interface logic.
 Easier to maintain.
 But java definition can also be useful :
 Adding components dynamically.
User Interfaces : XML Definition >> Example
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android=“http://schemas.android.com/apk/res/androi
d”
android:orientation="vertical”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/first_name”
/>
<EditText
android:layout_width=“match_parent"
android:layout_height="wrap_content"
android:id="@+id/first_name”
/>
</LinearLayout>
GroupView
Views
User Interfaces : Java Definition >> Example
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(
new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
TextView textView = new TextView(this);
textView.setText(R.string.first_name);
EditText editText = new EditText(this);
layout.addView(textView);
layout.addView(editText);
setContentView(layout);
}
User Interfaces : ID Attribute
 Ids are typically assigned in the layout XML files, and are used
to retrieve specific views inside the Activity code.
 You can ask ADT to generate one with the special syntax :
Instead of :
“@+id/resource_identifier”
“@id/resource_identifier”
User Interfaces : ID Attribute
 Example :
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/first_name”
/>
EditText txtFirstName =
(EditText)
findViewById(R.id.first_name);
User Interfaces : Layouts
 A layout is a ViewGroup which help us to position our views.
 A layout is also a view.
 A layout can contain other layouts.
 Common layouts provide by the SDK are :
 LinearLayout.
 RelativeLayout.
 FrameLayout.
 TableLayout.
 We’re going to see only the first one.
User Interfaces : Layouts >> LinearLayout
 A Layout that arranges its
children in a single column or a
single row.
 This layout is the more use in
Android development
 It can almost do everything
others can do.
 With nesting layout.
User Interfaces : Layouts >> LinearLayout : Component size
 The size of its components can be define with :
 In XML with layout_width and layout_height attributes.
 In Java with a LayoutParams object.
 Their values may be a dimension or one of the special
constants :
FILL_PARENT, MATCH_PARENT, WRAP_CONTENT
<TextView
android:layout_width="wrap_content"
android:layout_height=”10px"
/>
User Interfaces : Layouts >> LinearLayout : Weight
 Defined how views on the same
row share the layout size.
 Useful when you want that
several views share all the
screen.
 Example :
<Button
android:layout_width="wrap_content
"
android:layout_height=”wrap_conten
t”
android:layout_weight=”2”
android:layout_text=”weight=2"
/>
User Interfaces : Layouts >> LinearLayout : Gravity
 Specify how to align the text by the view's x- and/or y-axis
when the content is smaller than the view.
 Must be one or more (separated by '|') of the Gravity class
constant values :
 LEFT / RIGHT
 TOP / BOTTOM
 CENTER
 … <TextView
android:layout_width=”match_parent"
android:layout_height=“match_parent”
android:gravity=”top|right"
/>
User Interfaces : Layouts >> LinearLayout : Gravity
 Specify how to align the text by the view's x- and/or y-axis
when the content is smaller than the view.
 Must be one or more (separated by '|') of the Gravity class
constant values :
 LEFT / RIGHT
 TOP / BOTTOM
 CENTER
 … <TextView
android:layout_width=”match_parent"
android:layout_height=“match_parent”
android:gravity=”top|right"
/>
User Interfaces : Layouts >> LinearLayout : Padding
 By default, components are tightened each other.
 You can define space between them thanks to padding !
 Padding is defined as space between the edges of the view and
the view's content.
 Value in pixels.
 Five padding attributes exist :
 padding
 paddingLeft
 paddingRight
 paddingTop
 paddingBottom
User Interfaces : Layouts >> LinearLayout : Padding
 XML example :
 Java example :
<TextView
android:layout_width=”match_parent"
android:layout_height=“match_parent”
android:padding=”20dp"
/>
EditText txtFirstName = ... ;
// left, top, right, bottom
txtFirstName.setPadding(20, 30, 10, 20);
User Interfaces : TextView
 Displays text to the user.
 Can be editable
 But disable by default.
<TextView
android:layout_width=”match_parent"
android:layout_height=“match_parent”
android:gravity=”top|right"
/>
User Interfaces : EditText
 EditText is a subclass of TextView
 Editable by default !
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/first_name”
/>
User Interfaces : CheckBox
<CheckBox
android:id="@+id/checkbox”
android:layout_width="wrap_content”
android:layout_height="wrap_content”
android:text="check it out"
/>
 A check box is a two-states button that can be either checked
or unchecked.
User Interfaces : RadioButton
 A radio button is a two-states button that can be either
checked or unchecked.
 Contrary to checkbox, only one button by radio group can
be checked.
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/radio_group"
>
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Easy"
/>
...
</RadioGroup>
User Interfaces : Spinner
<Spinner
android:id="@+id/spinner”
android:layout_width=“match_parent”
android:layout_height="wrap_content”
android:prompt="@string/spinner_prompt”
/>
 A spinner is the Android version of the combo box.
User Interfaces : Spinner >> Adapter
String[] values = { "Easy", "Medium", "Hard" };
ListAdapter adapter =
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
values);
adapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item)
;
Spinner spinner = (Spinner)
findViewById(R.id.spinner);
spinner.setAdapter(adapter);
 To set spinner options, you need to use a ListAdapter object.
User Interfaces : AutoCompleteTextView
 An editable text view that shows completion suggestions
automatically while the user is typing.
<AutoCompleteTextView
android:id="@+id/autocomplete_planet”
android:layout_width=”match_parent”
android:layout_height="wrap_content”
/>
User Interfaces : Button
 Represents a push-button widget.
 Push-buttons can be pressed, or clicked, by the user to perform
an action.
<Button
android:id="@+id/my_button”
android:layout_width=”wrap_content”
android:layout_height="wrap_content”
android:text=“@string/button_text”
/>
User Interfaces : ImageButton
 Represents a push-button widget but with an image instead of
text inside.
<ImageButton
android:id="@+id/my_button”
android:layout_width=”wrap_content”
android:layout_height="wrap_content”
android:src="@drawable/logo_google"
/>
User Interfaces : ListView
 A view that shows items in a vertically scrolling list.
<ListView
android:id="@+id/my_list_view”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
/>
User Interfaces : ListView >> Adapter
ListView listView =
(ListView)
findViewById(R.id.my_list_view);
Cursor cursor = new
PersonDao(this).getAllPersons();
ListAdapter adapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor, new String[] { "name"
},
new int[] { android.R.id.text1
});
listView.setAdapter(adapter);
 To populate the list, you need to use an ListAdapter object
again.
User Interfaces : Adapters
 The bridge between a component and the data that backs the list.
 The most used concrete subclasses are :
 ArrayAdapter
 Adapter to map object arrays or object lists to a view.
 SimpleCursorAdapter
 Adapter to map columns of a cursor to a view.
 We’ll see more about curser later…
 Constructors of these classes take a resource id :
 The layout to apply to the item of the view
 You can use one of proposed by the SDK.
 You can define your own layout.
 Remember : android.R ≠ R
User Interfaces : Events
 With Android, all user actions are events
 Click
 Long click
 Key pressed
 Item selected
 …
 You can link behaviors to this events.
 The interception mechanism based on the Listener notion.
 As with Swing !
User Interfaces : Click Event
 To add a listener to a click event on a view :
 setOnClickListener(View.OnClickListener)
 OnClickListener is an inner interface of the View class.
 You have three possibilities :
 Make your activity implements it.
 Create a new class implementing it.
 Create an anonymous class.
User Interfaces : Click Event
 First solution :
public class MyActivity extends Activity implements
View.OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = (Button) findViewById(R.id.my_button);
button.setOnClickListener(this);
}
public void onClick(View view) {
// Display a notification popup during 1 second.
Toast.makeText(this, "Button clicked !", 1000).show();
}
}
User Interfaces : Click Event
 Second solution :
public class MyActivity extends Activity {
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = (Button)
findViewById(R.id.my_button);
button.setOnClickListener(new
ButtonClickListener());
}
}
public class ButtonClickListener implements
View.OnClickListener {
public void onClick(View view) {
// Display a notification popup during 1 second.
Toast.makeText(this, "Button clicked !",
1000).show();
}
}
User Interfaces : Click Event
 Third solution :
public class MyActivity extends Activity {
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = (Button)
findViewById(R.id.my_button);
button.setOnClickListener(new
View.OnClickListener() {
public void onClick(View view) {
// Display a notification popup during
1 second.
Toast.makeText(MyActivity.this,
“Clicked!", 1000)
.show();
}
});
Activités
Activity
 An activity is a sort of screen composed of several views and
controls.
 As many activities as application screens.
 Presentation layer of an application.
Activity
 Composed of two parts :
 The Activity Logic :
 Define in Java inside a class extending
android.app.Activity.
 The User Interface :
 Define either in Java inside the Activity class or
inside a XML file (in the folder /res/layout/).
Activity : example
 Activity class simple example :
package com.supinfo.hellodroid;
import android.app.Activity;
import android.os.Bundle;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Activity : example
 Layout file simple example :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android=“http://schemas.android.com/apk/res/and
roid”
android:orientation="vertical”
android:layout_width="fill_parent”
android:layout_height="fill_parent”
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello”
/>
</LinearLayout>
Activity lifecycle
 An activity can have three states :
 Active
 The activity is visible and has the user focus.
 Paused
 The activity is at least partly visible but doesn’t have
the focus.
 Stopped
 The activity is not
visible.
 Activity class defines methods to manage life cycle.
Activity lifecycle
Activity lifecycle
/**
* Appelée lorsque l’activité est créée.
* Permet de restaurer l’état de l’interface
* utilisateur grâce au paramètre savedInstanceState.
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Placez votre code ici
}
/**
* Appelée lorsque que l’activité a fini son cycle de vie.
* C’est ici que nous placerons notre code de libération
de mémoire, fermeture de fichiers et autres opérations
* de "nettoyage".
*/
}
@Override
public void onDestroy(){
// Placez votre code ici
super.onDestroy();
}
Activity lifecycle
/**
* Appelée lorsque l’activité démarre.
* Permet d’initialiser les contrôles.
*/
@Override
public void onStart(){
super.onStart();
// Placezvotre code ici
}
/**
*
Appelée lorsque l’activité passe en arrière plan.
* Libérez les écouteurs, arrêtez les threads, votre
activité
* peut disparaître de la mémoire.
*/
@Override
public void onStop(){
// Placez votre code ici
super.onStop();
/**
* Appelée lorsque l’activité sort de son état de veille.
*/
@Override
public void onRestart(){
super.onRestart();
//Placez votre code ici
}
/**
* Appelée lorsque que l’activité est suspendue.
* Stoppez les actions qui consomment des ressources.
* L’activité va passer en arrière-plan.
*/
@Override
public void onPause(){
//Placez votre code ici
super.onPause();
}
Activity lifecycle
/**
* Appelée après le démarrage ou une pause.
* Relancez les opérations arrêtées (threads).
* Mettez à jour votre application et vérifiez vos écouteurs.
*/
@Override
public void onResume(){
super.onResume();
// Placez votre code ici
}
Activity lifecycle
Activity : declaration
 To be usable, an activity must be declared
 Inside the AndroidManifest.xml file.
… <category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=”.ourActivity"
android:label="@string/app_name">
</activity>
</application>
...
Intent
Intent
 An intent is an abstract description of an operation to be
performed.
 We can use it to :
 Launch an Activity.
 Communicate with components like :
 Background Services.
 Broadcast Receivers.
 The first one is the most common usage
 We’ll only see it.
Intent : Launch an Activity
 To simply launch an activity :
 One of Instant constructors take only this two parameters :
 The context of the intent, here the activity instance creating
it.
 The component class used for the intent.
 startActivity(Intent) :
 An instance method of Activity class to start a new activity
with an intent.
Intent intent = new Intent(this,
ActivityToLaunch.class);
startActivity(intent);
Intent : Important remark
Remember :
An Activity have
to be declared
inside Android
Manifest file to
be launched.
Intent : Include extra data
 When you launch another activity, you often need to
communicate some information.
 You can use the intent methods below :
 void putExtra(…)
 Bundle getExtras(…)
 Supported types are :
 Primitives : byte, short, int, long, float, double, …
 Primitive Arrays : int[], long[], …
 Strings
 Serializable objects.
Intent : include extra data
 To put an extra data :
 To retrieve it in the launched Activity :
 Intent getIntent() :
 Return the intent that started this activity.
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("smthg", "Hi Activity.");
startActivity(intent, MY_ACTIVITY_CODE);
Bundle extras = getIntent().getExtras();
if(extras != null) {
String message = extras.getString("smthg");
}
Persistence
Persistence: Presentation
 Android provide four ways to store data :
 Instance State.
 Shared Preferences.
 SQLite databases.
 Files.
 We’re going to see the first three.
Persistence: Presentation
 To put an extra data :
 To retrieve it in the launched Activity :
 Intent getIntent() :
 Return the intent that started this activity.
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("smthg", "Hi Activity.");
startActivity(intent, MY_ACTIVITY_CODE);
Bundle extras = getIntent().getExtras();
if(extras != null) {
String message = extras.getString("smthg");
}
Persistence: Instance State
 You have seen earlier activities life cycle.
 A background activity can be unloaded if another one need
memory.
 How to save activity state to allow user to retrieve his activity as
before ?
 Thanks to Instance State !
 We’re going to see the two
activity methods to manage
instance state :
onSaveInstanceState(…)
onRestoreInstanceState(…)
Persistence: Instance State
 onSaveInstanceState(Bundle)
 Called to retrieve per-instance state from an activity before
being killed so that the state can be restored in
onCreate(Bundle) or onRestoreInstanceState(Bundle) (the
Bundle populated by this method will be passed to both).
 onRestoreInstanceState(Bundle)
 This method is called after onStart() when the activity is being
re-initialized from a previously saved state, given here in
Bundle type parameter.
Persistence: Instance State
 By default, Instance State save the values of all views with id
attribute.
 If you want to save more information, just override the two
methods we have just seen.
private String myInformation;
...
protected void onSaveInstanceState(Bundle outState)
{
outState.putString("anotherInformation",
myInformation);
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle
savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
myInformation =
savedInstanceState.getString("anotherInformat
ion");
}
Persistence: Shared Preferences
 Share across all components in an application.
 Set of key/value pair.
 Can only store boolean, int, long, float and String values.
 Permission can be given :
 MODE_PRIVATE
 Default value, the created file is only accessible by the
application that created it.
 MODE_WORD_READABLE
 Other applications can read the file but not modify it.
 MODE_WORD_WRITABLE
 Other applications can modify the file.
Persistence: Shared Preferences
 Examples :
 Save shared preferences :
SharedPreferences prefs =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(“username”, “Droid”);
editor.putBoolean(“isAdmin”, true);
editor.commit();
Persistence: Shared Preferences
 Examples :
 Retrieve shared preferences :
SharedPreferences prefs =
getPreferences(Context.MODE_PRIVATE);
// If there is no value for “username”, return null
String username = prefs.getString(“username”, null);
// If there is no value for “isAdmin”, return false
boolean admin = prefs.getBoolean(“isAdmin”, false);
// If there is no value for “id”, return zero
long id = prefs.getLong(“id”, 0L);
Persistence: SQLiteDatabases
 Relational Database Management System.
 Useful to stock complex data.
 Each database is dedicated to only one application.
 An application can have several databases.
 To share data with another application, you can use a Content
Provider (out of the course's scope).
Persistence: SQLiteDatabases
 Don’t design your SQLite database as a MySQL or PostgreSQL
ones.
 Mobile devices are not dedicated database server
 Little storage space.
 Little memory.
 Store only what you need.
 Avoid frequent requests.
 Design SQLite databases with :
 A simple structure.
 Data easily identifiable.
 Don’t store binary data !
Persistence: SQLiteOpenHelper
 To simplify your code to create or update a Database schema,
the SDK propose you a Helper class named :
SQLiteOpenHelper.
 To use it, create your proper class and extend it.
Abstract
Methods
Persistence: SQLiteOpenHelper
 Example :
public class MyOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME =
“my.db”;
private static final int DATABASE_VERSION = 2;
private static final String TABLE_NAME =
”persons";
private static final String TABLE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
”id INTEGER PRIMARY KEY AUTOINCREMENT, " +
“name TEXT NOT NULL);";
public MyOpenHelper(Context context) {
super(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
...
Persistence: SQLiteOpenHelper
 Example :
...
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
public void onUpgrade(SQLiteDatabase db,
int oldVersion, int newVersion) {
Log.w("Example", ”Upgrading database, this
will drop”
+ “tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " +
TABLE_NAME);
onCreate(db);
}
}
Persistence: SQLiteDatabase
 This class provides two other methods very useful :
 SQLiteDatabase getWritableDatabase()
 Return a SQLiteDatabase instance to read or write in
the Database. Throw an exception if the database
cannot be opened for writing (bad permission or full
disk).
 SQLiteDatabase getReadableDatabase()
 Return a SQLiteDatabase instance with read-only
access to the database.
 Both will create the database if it doesn’t exist.
Persistence: SQLiteDatabase
 Exposes methods to manage a SQLite database.
 Has methods to create, delete, execute SQL commands, and
perform other common database management tasks.
 We’re going to see some useful methods :
 void execSQL(...)
 long insert(…)
 int update(…)
 int delete(…)
 Cursor query(…)
Persistence: SQLiteDatabase
 void execSQL(String sql) :
 Execute a single SQL statement that is not a query.
 For example, CREATE TABLE, DELETE, INSERT, etc.
 Example :
SQLiteDatabase db = ...
db.execSQL("DROP TABLE IF EXISTS
my_table");
Persistence: SQLiteDatabase
 long insert (String table, String nullColumnHack,
ContentValues values) :
 Convenience method for inserting a row into the database.
 Three parameters :
 table : The table to insert the row into.
 nullColumnHack :
 SQL doesn't allow inserting a completely empty row.
 If initialValues is empty this column will explicitly be
assigned a NULL value.
 values :
 Map containing the column values for the row
 The keys should be the column names.
 The values the column values.
Persistence: SQLiteDatabase
 long insert (String table, String nullColumnHack,
ContentValues values) :
 Return the row ID of the inserted row.
 Example :
SQLiteDatabase db = ...
ContentValues values = new ContentValues();
values.put(“name”, “bentahar”);
db.insert(“persons”, null, values);
Persistence: SQLiteDatabase
 int update (String table, ContentValues values,
String whereClause, String[] whereArgs) :
 Convenience method for updating rows in the database.
 Four parameters :
 table : the table to update in.
 values : a map from column names to new column values.
 whereClause : the optional WHERE clause to apply when
updating.
 whereArgs : an array of the value to apply to the WHERE
clause.
 Return the number of rows affected.
Persistence: SQLiteDatabase
 int update (String table, ContentValues values,
String whereClause, String[] whereArgs) :
 Example :
SQLiteDatabase db = ...
ContentValues values = new ContentValues();
values.put("name", ”Zakaria");
String[] whereArgs = { "1" };
db.update(“persons”, values, "id=?", whereArgs);
Persistence: SQLiteDatabase
 int delete (String table, String whereClause,
String[] whereArgs) :
 Convenience method for deleting rows in the Database.
 Three parameters :
 table : the table to delete from.
 whereClause : the optional WHERE clause to apply
when deleting.
 whereArgs : an array of the value to apply to the
WHERE clause.
 Return the number of rows affected.
Persistence: SQLiteDatabase
 int delete (String table, String whereClause,
String[] whereArgs) :
 Example :
SQLiteDatabase db = ...
String[] whereArgs = { "1" };
db.delete("persons", "id=?", whereArgs);
Persistence: SQLiteDatabase
 Cursor query(String table, String[] columns,
String selection, String[] selectionArgs,
String groupBy, String having,
String orderBy) :
 Query the given table, returning a Cursor over the result
set.
 Seven parameters :
 table : The table name to compile the query.
 columns : A list of which columns to return.
 selection : A filter declaring which rows to return,
formatted as an SQL WHERE clause.
Persistence: SQLiteDatabase
 Cursor query(String table, String[] columns,
String selection, String[] selectionArgs,
String groupBy, String having,
String orderBy) :
 Seven parameters :
 selectionArgs : You may include ?s in selection, which will
be replaced by the values from selectionArgs.
 groupBy : A filter declaring how to group rows, formatted
as an SQL GROUP BY clause.
 having : A filter declare which row groups to include in the
cursor, if row grouping is being used, formatted as an SQL
HAVING clause.
 orderBy : How to order the rows, formatted as an SQL
ORDER BY clause.
Persistence: SQLiteDatabase
 Cursor query(String table, String[] columns,
String selection, String[] selectionArgs,
String groupBy, String having,
String orderBy) :
 Example :
SQLiteDatabase db = ...
String[] columns = { ID_COLUMN, NAME_COLUMN };
String[] params = { “Cartman” };
Cursor result = db.query(TABLE_NAME, columns,
”name=?",
params, null, null, null, "1");
Persistence: Cursor
 Provide access to the result set returned by a database query.
 Methods commonly used are :
 getCount() : returns the number of rows.
 moveToFirst() : moves the cursor to the first row.
 moveToNext() : moves the cursor to the next line.
 isAfterLast() : returns true if the cursor position is after the
last row.
 getColumnNames() : returns a string array holding the
names of all of the columns in the result set.
 getColumnIndex(String name) : return the index of the
corresponding column name.
Persistence: Cursor
String[] columns = { “id”, “name”};
Cursor result = db.query(“persons”, columns, null,
null, null, null, null);
List<Person> persons = new ArrayList<Person>();
result.moveToFirst();
while(!result.isAfterLast()) {
Person person = new Person();
person.setId(result.getLong(0));
person.setName(result.getString(1));
persons.add(person);
result.moveToNext();
}
result.close();
return persons;
 Example of use :
Android cours

More Related Content

What's hot

Eclipse & android setup
Eclipse & android setupEclipse & android setup
Eclipse & android setupChina Bigs
 
Titanium Studio [Updated - 18/12/2011]
Titanium Studio [Updated - 18/12/2011]Titanium Studio [Updated - 18/12/2011]
Titanium Studio [Updated - 18/12/2011]Sentinel Solutions Ltd
 
Automated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracerAutomated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracerKyungmin Lee
 
1 introduction of android
1 introduction of android1 introduction of android
1 introduction of androidakila_mano
 
Synapseindia android apps intro to android development
Synapseindia android apps  intro to android developmentSynapseindia android apps  intro to android development
Synapseindia android apps intro to android developmentSynapseindiappsdevelopment
 
BlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM Europe
BlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM EuropeBlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM Europe
BlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM EuropeMariano Carrizo
 
IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016Trayan Iliev
 
Visual Studio2010 Product Overview
Visual Studio2010 Product OverviewVisual Studio2010 Product Overview
Visual Studio2010 Product Overviewjanadbest
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentanistar sung
 
Introduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumIntroduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumAaron Saunders
 
Android In A Nutshell
Android In A NutshellAndroid In A Nutshell
Android In A NutshellTed Chien
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialEd Zel
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialkatayoon_bz
 
Cross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache CordovaCross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache CordovaIvano Malavolta
 

What's hot (20)

Android
Android Android
Android
 
Eclipse & android setup
Eclipse & android setupEclipse & android setup
Eclipse & android setup
 
Titanium Studio [Updated - 18/12/2011]
Titanium Studio [Updated - 18/12/2011]Titanium Studio [Updated - 18/12/2011]
Titanium Studio [Updated - 18/12/2011]
 
Automated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracerAutomated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracer
 
1 introduction of android
1 introduction of android1 introduction of android
1 introduction of android
 
Synapseindia android apps intro to android development
Synapseindia android apps  intro to android developmentSynapseindia android apps  intro to android development
Synapseindia android apps intro to android development
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
BlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM Europe
BlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM EuropeBlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM Europe
BlackBerry10 apps with Adobe AIR & Apache Flex - BlackBerry JAM Europe
 
IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016
 
Visual Studio2010 Product Overview
Visual Studio2010 Product OverviewVisual Studio2010 Product Overview
Visual Studio2010 Product Overview
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app development
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Introduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumIntroduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator Titanium
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android In A Nutshell
Android In A NutshellAndroid In A Nutshell
Android In A Nutshell
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Mono for android
Mono for androidMono for android
Mono for android
 
Cross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache CordovaCross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache Cordova
 

Viewers also liked

Android Studio, premier contact
Android Studio, premier contactAndroid Studio, premier contact
Android Studio, premier contactJasmine Conseil
 
Développement Android
Développement AndroidDéveloppement Android
Développement AndroidFranck SIMON
 
Etude Android - Surikate
Etude Android - SurikateEtude Android - Surikate
Etude Android - SurikateUlrich Rozier
 
In01 - Programmation Android - 07 - techniques avancées
In01 - Programmation Android - 07 - techniques avancéesIn01 - Programmation Android - 07 - techniques avancées
In01 - Programmation Android - 07 - techniques avancéesYann Caron
 
01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)TECOS
 
Ma présentation PFE : Application Android & Site Web
Ma présentation PFE : Application Android & Site WebMa présentation PFE : Application Android & Site Web
Ma présentation PFE : Application Android & Site WebHarrathi Mohamed
 
Télémétrie d’openstack
Télémétrie d’openstackTélémétrie d’openstack
Télémétrie d’openstackTECOS
 
Summer internship
Summer internshipSummer internship
Summer internshipTECOS
 
Mobile certified
Mobile certifiedMobile certified
Mobile certifiedTECOS
 
Intelligence Artificielle - Systèmes experts
Intelligence Artificielle - Systèmes expertsIntelligence Artificielle - Systèmes experts
Intelligence Artificielle - Systèmes expertsMohamed Heny SELMI
 
Formation au Mobile Commerce (m-commerce)
Formation au Mobile Commerce (m-commerce)Formation au Mobile Commerce (m-commerce)
Formation au Mobile Commerce (m-commerce)SimaWay Simaway
 
سيرتي الذاتية بالغة العربية
سيرتي الذاتية بالغة العربيةسيرتي الذاتية بالغة العربية
سيرتي الذاتية بالغة العربيةTaoufik Chaieb
 
Data mining - Introduction générale
Data mining - Introduction généraleData mining - Introduction générale
Data mining - Introduction généraleMohamed Heny SELMI
 

Viewers also liked (20)

Android Studio, premier contact
Android Studio, premier contactAndroid Studio, premier contact
Android Studio, premier contact
 
Programmation sous Android
Programmation sous AndroidProgrammation sous Android
Programmation sous Android
 
Développement Android
Développement AndroidDéveloppement Android
Développement Android
 
Etude Android - Surikate
Etude Android - SurikateEtude Android - Surikate
Etude Android - Surikate
 
In01 - Programmation Android - 07 - techniques avancées
In01 - Programmation Android - 07 - techniques avancéesIn01 - Programmation Android - 07 - techniques avancées
In01 - Programmation Android - 07 - techniques avancées
 
01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)
 
Ma présentation PFE : Application Android & Site Web
Ma présentation PFE : Application Android & Site WebMa présentation PFE : Application Android & Site Web
Ma présentation PFE : Application Android & Site Web
 
Les Fragments
Les FragmentsLes Fragments
Les Fragments
 
Télémétrie d’openstack
Télémétrie d’openstackTélémétrie d’openstack
Télémétrie d’openstack
 
Summer internship
Summer internshipSummer internship
Summer internship
 
Mobile certified
Mobile certifiedMobile certified
Mobile certified
 
Mta
MtaMta
Mta
 
Final
FinalFinal
Final
 
Android
AndroidAndroid
Android
 
Intelligence Artificielle - Systèmes experts
Intelligence Artificielle - Systèmes expertsIntelligence Artificielle - Systèmes experts
Intelligence Artificielle - Systèmes experts
 
Data mining - Associativité
Data mining - AssociativitéData mining - Associativité
Data mining - Associativité
 
Formation au Mobile Commerce (m-commerce)
Formation au Mobile Commerce (m-commerce)Formation au Mobile Commerce (m-commerce)
Formation au Mobile Commerce (m-commerce)
 
سيرتي الذاتية بالغة العربية
سيرتي الذاتية بالغة العربيةسيرتي الذاتية بالغة العربية
سيرتي الذاتية بالغة العربية
 
Data mining - Introduction générale
Data mining - Introduction généraleData mining - Introduction générale
Data mining - Introduction générale
 
Arbre de décision
Arbre de décisionArbre de décision
Arbre de décision
 

Similar to Android cours

Introduction to android
Introduction to androidIntroduction to android
Introduction to androidzeelpatel0504
 
architecture of android.pptx
architecture of android.pptxarchitecture of android.pptx
architecture of android.pptxallurestore
 
Android development tutorial
Android development tutorialAndroid development tutorial
Android development tutorialnazzf
 
Android development tutorial
Android development tutorialAndroid development tutorial
Android development tutorialMohammad Taj
 
Android development-tutorial
Android development-tutorialAndroid development-tutorial
Android development-tutorialilias ahmed
 
Questions About Android Application Development
Questions About Android Application DevelopmentQuestions About Android Application Development
Questions About Android Application DevelopmentAdeel Rasheed
 
Intro To Android App Development
Intro To Android App DevelopmentIntro To Android App Development
Intro To Android App DevelopmentMike Kvintus
 
Android overview
Android overviewAndroid overview
Android overviewHas Taiar
 
Android app development ppt
Android app development pptAndroid app development ppt
Android app development pptsaitej15
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answerskavinilavuG
 
Android development training programme Day 1
Android development training programme Day 1Android development training programme Day 1
Android development training programme Day 1DHIRAJ PRAVIN
 
Evolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s VersionsEvolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s Versionsijtsrd
 
Technology and Android.pptx
Technology and Android.pptxTechnology and Android.pptx
Technology and Android.pptxmuthulakshmi cse
 
Android 1-intro n architecture
Android 1-intro n architectureAndroid 1-intro n architecture
Android 1-intro n architectureDilip Singh
 

Similar to Android cours (20)

Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
PPT Companion to Android
PPT Companion to AndroidPPT Companion to Android
PPT Companion to Android
 
architecture of android.pptx
architecture of android.pptxarchitecture of android.pptx
architecture of android.pptx
 
Android development tutorial
Android development tutorialAndroid development tutorial
Android development tutorial
 
Android development tutorial
Android development tutorialAndroid development tutorial
Android development tutorial
 
Android development-tutorial
Android development-tutorialAndroid development-tutorial
Android development-tutorial
 
Questions About Android Application Development
Questions About Android Application DevelopmentQuestions About Android Application Development
Questions About Android Application Development
 
Intro To Android App Development
Intro To Android App DevelopmentIntro To Android App Development
Intro To Android App Development
 
Android overview
Android overviewAndroid overview
Android overview
 
Aptech Apps
Aptech Apps Aptech Apps
Aptech Apps
 
Android dev o_auth
Android dev o_authAndroid dev o_auth
Android dev o_auth
 
Android apps
Android appsAndroid apps
Android apps
 
Introduction to Android Environment
Introduction to Android EnvironmentIntroduction to Android Environment
Introduction to Android Environment
 
Android app development ppt
Android app development pptAndroid app development ppt
Android app development ppt
 
Android
AndroidAndroid
Android
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
 
Android development training programme Day 1
Android development training programme Day 1Android development training programme Day 1
Android development training programme Day 1
 
Evolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s VersionsEvolution of Android Operating System and it’s Versions
Evolution of Android Operating System and it’s Versions
 
Technology and Android.pptx
Technology and Android.pptxTechnology and Android.pptx
Technology and Android.pptx
 
Android 1-intro n architecture
Android 1-intro n architectureAndroid 1-intro n architecture
Android 1-intro n architecture
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Android cours

  • 1. Pr. Zakaria Bentahar À l’académie internationale d’aviation civile (AIAC), Casablanca, Maroc
  • 2. Plan Android : qu'est ce que c'est ? et l'Open Handset Alliance ? Pourquoi Android ? Positionnement par rapport à son environnement Historique de 2005 à nos jours Les différentes versions d’Android Architecture du système Android
  • 3. Plan La structure d’un projet Android Création des interfaces utilisateurs Ressources Activités Intent Persistence des données (Fichiers, SQLite)
  • 5. Android est un système d'exploitation pour téléphone portable de nouvelle génération développé par Google. Celui ci met à disposition un kit de développement (SDK) basé sur le langage Java.
  • 6. L'Open Handset Alliance (abrégé OHA) est un consortium de plusieurs entreprises dont le but est de développer des normes ouvertes pour les appareils de téléphonie mobile. Le consortium a été créé le 5 novembre 2007 à l'initiative de Google qui a su fédérer autour de lui 34 compagnies
  • 7.
  • 9. Rovio une entreprise fondé par trois étudiants d'une université de technology en Finland a eu des revenues d'environ €75.4 million en 2011 grâce à un jeu gratuit Angry Birds, ils ont gagné plus d'un million de dollars par mois, ceci à travers les publicités qui se lancent automatiquement suite à chaque lancement du jeu.
  • 10. Instagram est une application et un service de partage des photos conçu par un ingénieur avec deux ans d'expériences en Gmail et un ingénieur étudiant brézilien résidant en Californie , Facebook l'a acheté d'eux en 1 billion $ Cach, il était uploaded au niveau de App Store comme c'est le cas pour le reste des applications Android et il a eu sa réputation grâce aux nombres de téléchargement.
  • 11. WhatsApp est une application de messagerie instantannée réalisé par deux anciens combattants de Yahoo, cette application qui coute juste 0.99$ après une année gratuite a réussit a faire une fortune même si la societé n'a pas dévoilé ses revenues mais juste en la comparant avec le nombre d'utilisation de Instagram qu'a acquiert facebook , elle a eu plus d'utilisateurs par la suite plus de revenues.
  • 12. Talking Tom Cat c'est un jeu qui étaient téléchargé plus de 400 million fois réalisé par une societé spécialisée dans la réalisation des applications payantes de divertissement, alors que le meilleur nombre de téléchargement d'un logiciel comme Avast a eu juste 340987 nombre de téléchargement dans le site le plus populaire de téléchargement télecharger.com
  • 13. Positionnement par rappot à son environnement
  • 14.
  • 17. Versions Pour plus de details : http://fr.wikipedia.org/wiki/Historique_des_versions_d' Android
  • 19. Architecture La plate-forme Android est composée de différentes couches : un noyau Linux qui lui confère notamment des caractéristiques multitâches ; des bibliothèques graphiques, multimédias ; une machine virtuelle Java adaptée : la Dalvik Virtual Machine ; un framework applicatif proposant des fonctionnalités de gestion de fenêtres, de téléphonie, de gestion de contenu... ; des applications dont un navigateur web, une gestion des contacts, un calendrier…
  • 22. SDK Le SDK est un ensemble d’outils qui permet aux développeurs et aux entreprises de créer des applications. http://developer.android.com/sdk/index.html
  • 25. Configuration de Eclipse: Installation de ADT (Android Development Tools)  crée et débogue des applications Android facile et plus rapide  donne accès à d'autres outils de développement Android à l'intérieur de Eclipse.  fournit un éditeur de code Android qui aide à écrire du code XML valide pour le fichier de configuration et les fichiers de ressources  exporte le projet dans un APK signé.
  • 27.
  • 28. 1) Installer SDK 2) Installer ADT 3) Configurer SDK dans Eclipse Etapes de configuration de l’environnement de développement
  • 30. CONFIGURER UN APPAREIL VIRTUEL ANDROID AVD (Android Virtual Devices) est un émulateur qui joue le rôle de smartphone
  • 31. CONFIGURER UN APPAREIL VIRTUEL ANDROID Window > Android AVD Manager
  • 34. Structure du projet : gen  Contain Java files auto-generated by ADT.  Contain the class R :  Special static class.  Reference the data contained in resource files.  Contain one static inner class by resource type. public final class R{ public static final class drawable { public static final int icon=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } ... //code omitted }
  • 35. Structure du projet : assets  Contain asset files  Quite similar to resources.  Accessed in a classic file manipulation style  With stream of bytes manipulation.  Need to use AssertManager class to open them.  Not for an usage as extensive as resources.
  • 36. Structure du projet : androidManifest.xml  Mandatory file in every Android projects.  Contain information needed by Android to run the application  Package name of the application.  List of Activities, Services, Broadcast Receivers, …  Permissions needed by the application.  etc…
  • 40. Resources : Presentation  Android externalize resources like :  Images.  Strings.  User Interface description.  …  Easier to manage and maintain them.  Contained inside the res folder.
  • 41. Resources : Use the resources  Resources are accessible inside the code thanks to the static class : R.  This class is automatically generated by ADT.  When you add a resource inside the res folder, ADT add a reference to it inside the R class.  The syntax to retrieve a resource reference is : R.resource_type.resource_name
  • 42. Resources : Example // Define the layout of an activity setContentView(R.layout.my_screen); // Retrieve the application name Resources resources = getResources(); String appName = resources.getString(R.string.app_name); public final class R{ public static final class string { public static final int app_name=0x7f020000; } public static final class layout { public static final int my_screen=0x7f030000; } ... //code omitted }
  • 43. Resources : System Resources  Android already includes a number of resources  Predefined Colors.  Predefined Strings.  Predefined Images.  Examples : ... <TextView android:layout_width="fill_parent" android:layout_height="wrap_content” android:textColor="@android:color/darker_gray" android:text="@string/hello” /> ... String cancel = resources.getString(android.R.string.cancel);
  • 44. Resources : Simple Values  Simple values are stored in XML files inside /res/values folder.  You can declare  Strings  You can use the HTML tags <b>, <i> and <u>.  Colors  Accept #RGB, #ARGB, #RRGGBB and #AARRGGBB format.  Dimensions  In pixels (px), inches (in), millimeters (mm), points (pt), density-independent pixel (dp) or scale-independent pixel (sp),  Arrays  Of Integers or Strings.
  • 45. Resources : simple values’ examples <?xml version="1.0" encoding="utf-8"?> <resources> <color name="Cyan">#00FFFF</color> <string name="first_name">zakaria</string> <string-array name="my_array"> <item>A string</item> <item>Another String</item> </string-array> <integer-array name="my_other_array"> <item>123</item> <item>456</item> </integer-array> <dimen name="my_dimension">4dp</dimen> <dimen name="text_size">4px</dimen> </resources>
  • 46. Resources : Images  Android accept different bitmap format for resources :  PNG (advised by the documentation)  JPEG  GIF (deprecated)  From Android 1.6, three folders :  drawable-hdpi : resource for high-resolution screens.  drawable-mdpi : resources for medium-resolution screens.  drawable-ldpi : resources for low-resolution screens.
  • 48. User Interfaces  A user interface is a set of graphical components like :  Button.  Text.  Form field.  Component composed of other components…  This components are called Views.  The last one is a special view called ViewGroup.
  • 50. User Interfaces  User interfaces can be defined :  In XML, inside a layout resource file.  Directly in the Activity code.  We’re going to see both.
  • 51. User Interfaces : XML Definition VS Java Definition  Use XML layout to define user interfaces :  Separate interface structure and interface logic.  Easier to maintain.  But java definition can also be useful :  Adding components dynamically.
  • 52. User Interfaces : XML Definition >> Example <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/androi d” android:orientation="vertical” android:layout_width=“match_parent” android:layout_height=“match_parent” > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/first_name” /> <EditText android:layout_width=“match_parent" android:layout_height="wrap_content" android:id="@+id/first_name” /> </LinearLayout> GroupView Views
  • 53. User Interfaces : Java Definition >> Example public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); layout.setLayoutParams( new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); TextView textView = new TextView(this); textView.setText(R.string.first_name); EditText editText = new EditText(this); layout.addView(textView); layout.addView(editText); setContentView(layout); }
  • 54. User Interfaces : ID Attribute  Ids are typically assigned in the layout XML files, and are used to retrieve specific views inside the Activity code.  You can ask ADT to generate one with the special syntax : Instead of : “@+id/resource_identifier” “@id/resource_identifier”
  • 55. User Interfaces : ID Attribute  Example : <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/first_name” /> EditText txtFirstName = (EditText) findViewById(R.id.first_name);
  • 56. User Interfaces : Layouts  A layout is a ViewGroup which help us to position our views.  A layout is also a view.  A layout can contain other layouts.  Common layouts provide by the SDK are :  LinearLayout.  RelativeLayout.  FrameLayout.  TableLayout.  We’re going to see only the first one.
  • 57. User Interfaces : Layouts >> LinearLayout  A Layout that arranges its children in a single column or a single row.  This layout is the more use in Android development  It can almost do everything others can do.  With nesting layout.
  • 58. User Interfaces : Layouts >> LinearLayout : Component size  The size of its components can be define with :  In XML with layout_width and layout_height attributes.  In Java with a LayoutParams object.  Their values may be a dimension or one of the special constants : FILL_PARENT, MATCH_PARENT, WRAP_CONTENT <TextView android:layout_width="wrap_content" android:layout_height=”10px" />
  • 59. User Interfaces : Layouts >> LinearLayout : Weight  Defined how views on the same row share the layout size.  Useful when you want that several views share all the screen.  Example : <Button android:layout_width="wrap_content " android:layout_height=”wrap_conten t” android:layout_weight=”2” android:layout_text=”weight=2" />
  • 60. User Interfaces : Layouts >> LinearLayout : Gravity  Specify how to align the text by the view's x- and/or y-axis when the content is smaller than the view.  Must be one or more (separated by '|') of the Gravity class constant values :  LEFT / RIGHT  TOP / BOTTOM  CENTER  … <TextView android:layout_width=”match_parent" android:layout_height=“match_parent” android:gravity=”top|right" />
  • 61. User Interfaces : Layouts >> LinearLayout : Gravity  Specify how to align the text by the view's x- and/or y-axis when the content is smaller than the view.  Must be one or more (separated by '|') of the Gravity class constant values :  LEFT / RIGHT  TOP / BOTTOM  CENTER  … <TextView android:layout_width=”match_parent" android:layout_height=“match_parent” android:gravity=”top|right" />
  • 62. User Interfaces : Layouts >> LinearLayout : Padding  By default, components are tightened each other.  You can define space between them thanks to padding !  Padding is defined as space between the edges of the view and the view's content.  Value in pixels.  Five padding attributes exist :  padding  paddingLeft  paddingRight  paddingTop  paddingBottom
  • 63. User Interfaces : Layouts >> LinearLayout : Padding  XML example :  Java example : <TextView android:layout_width=”match_parent" android:layout_height=“match_parent” android:padding=”20dp" /> EditText txtFirstName = ... ; // left, top, right, bottom txtFirstName.setPadding(20, 30, 10, 20);
  • 64. User Interfaces : TextView  Displays text to the user.  Can be editable  But disable by default. <TextView android:layout_width=”match_parent" android:layout_height=“match_parent” android:gravity=”top|right" />
  • 65. User Interfaces : EditText  EditText is a subclass of TextView  Editable by default ! <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/first_name” />
  • 66. User Interfaces : CheckBox <CheckBox android:id="@+id/checkbox” android:layout_width="wrap_content” android:layout_height="wrap_content” android:text="check it out" />  A check box is a two-states button that can be either checked or unchecked.
  • 67. User Interfaces : RadioButton  A radio button is a two-states button that can be either checked or unchecked.  Contrary to checkbox, only one button by radio group can be checked. <RadioGroup android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/radio_group" > <RadioButton android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Easy" /> ... </RadioGroup>
  • 68. User Interfaces : Spinner <Spinner android:id="@+id/spinner” android:layout_width=“match_parent” android:layout_height="wrap_content” android:prompt="@string/spinner_prompt” />  A spinner is the Android version of the combo box.
  • 69. User Interfaces : Spinner >> Adapter String[] values = { "Easy", "Medium", "Hard" }; ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, values); adapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item) ; Spinner spinner = (Spinner) findViewById(R.id.spinner); spinner.setAdapter(adapter);  To set spinner options, you need to use a ListAdapter object.
  • 70. User Interfaces : AutoCompleteTextView  An editable text view that shows completion suggestions automatically while the user is typing. <AutoCompleteTextView android:id="@+id/autocomplete_planet” android:layout_width=”match_parent” android:layout_height="wrap_content” />
  • 71. User Interfaces : Button  Represents a push-button widget.  Push-buttons can be pressed, or clicked, by the user to perform an action. <Button android:id="@+id/my_button” android:layout_width=”wrap_content” android:layout_height="wrap_content” android:text=“@string/button_text” />
  • 72. User Interfaces : ImageButton  Represents a push-button widget but with an image instead of text inside. <ImageButton android:id="@+id/my_button” android:layout_width=”wrap_content” android:layout_height="wrap_content” android:src="@drawable/logo_google" />
  • 73. User Interfaces : ListView  A view that shows items in a vertically scrolling list. <ListView android:id="@+id/my_list_view” android:layout_width=”fill_parent” android:layout_height=”fill_parent” />
  • 74. User Interfaces : ListView >> Adapter ListView listView = (ListView) findViewById(R.id.my_list_view); Cursor cursor = new PersonDao(this).getAllPersons(); ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[] { "name" }, new int[] { android.R.id.text1 }); listView.setAdapter(adapter);  To populate the list, you need to use an ListAdapter object again.
  • 75. User Interfaces : Adapters  The bridge between a component and the data that backs the list.  The most used concrete subclasses are :  ArrayAdapter  Adapter to map object arrays or object lists to a view.  SimpleCursorAdapter  Adapter to map columns of a cursor to a view.  We’ll see more about curser later…  Constructors of these classes take a resource id :  The layout to apply to the item of the view  You can use one of proposed by the SDK.  You can define your own layout.  Remember : android.R ≠ R
  • 76. User Interfaces : Events  With Android, all user actions are events  Click  Long click  Key pressed  Item selected  …  You can link behaviors to this events.  The interception mechanism based on the Listener notion.  As with Swing !
  • 77. User Interfaces : Click Event  To add a listener to a click event on a view :  setOnClickListener(View.OnClickListener)  OnClickListener is an inner interface of the View class.  You have three possibilities :  Make your activity implements it.  Create a new class implementing it.  Create an anonymous class.
  • 78. User Interfaces : Click Event  First solution : public class MyActivity extends Activity implements View.OnClickListener { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button button = (Button) findViewById(R.id.my_button); button.setOnClickListener(this); } public void onClick(View view) { // Display a notification popup during 1 second. Toast.makeText(this, "Button clicked !", 1000).show(); } }
  • 79. User Interfaces : Click Event  Second solution : public class MyActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button button = (Button) findViewById(R.id.my_button); button.setOnClickListener(new ButtonClickListener()); } } public class ButtonClickListener implements View.OnClickListener { public void onClick(View view) { // Display a notification popup during 1 second. Toast.makeText(this, "Button clicked !", 1000).show(); } }
  • 80. User Interfaces : Click Event  Third solution : public class MyActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button button = (Button) findViewById(R.id.my_button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Display a notification popup during 1 second. Toast.makeText(MyActivity.this, “Clicked!", 1000) .show(); } });
  • 82. Activity  An activity is a sort of screen composed of several views and controls.  As many activities as application screens.  Presentation layer of an application.
  • 83. Activity  Composed of two parts :  The Activity Logic :  Define in Java inside a class extending android.app.Activity.  The User Interface :  Define either in Java inside the Activity class or inside a XML file (in the folder /res/layout/).
  • 84. Activity : example  Activity class simple example : package com.supinfo.hellodroid; import android.app.Activity; import android.os.Bundle; public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
  • 85. Activity : example  Layout file simple example : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/and roid” android:orientation="vertical” android:layout_width="fill_parent” android:layout_height="fill_parent” > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello” /> </LinearLayout>
  • 86. Activity lifecycle  An activity can have three states :  Active  The activity is visible and has the user focus.  Paused  The activity is at least partly visible but doesn’t have the focus.  Stopped  The activity is not visible.  Activity class defines methods to manage life cycle.
  • 88. Activity lifecycle /** * Appelée lorsque l’activité est créée. * Permet de restaurer l’état de l’interface * utilisateur grâce au paramètre savedInstanceState. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Placez votre code ici } /** * Appelée lorsque que l’activité a fini son cycle de vie. * C’est ici que nous placerons notre code de libération de mémoire, fermeture de fichiers et autres opérations * de "nettoyage". */ } @Override public void onDestroy(){ // Placez votre code ici super.onDestroy(); }
  • 89. Activity lifecycle /** * Appelée lorsque l’activité démarre. * Permet d’initialiser les contrôles. */ @Override public void onStart(){ super.onStart(); // Placezvotre code ici } /** * Appelée lorsque l’activité passe en arrière plan. * Libérez les écouteurs, arrêtez les threads, votre activité * peut disparaître de la mémoire. */ @Override public void onStop(){ // Placez votre code ici super.onStop();
  • 90. /** * Appelée lorsque l’activité sort de son état de veille. */ @Override public void onRestart(){ super.onRestart(); //Placez votre code ici } /** * Appelée lorsque que l’activité est suspendue. * Stoppez les actions qui consomment des ressources. * L’activité va passer en arrière-plan. */ @Override public void onPause(){ //Placez votre code ici super.onPause(); } Activity lifecycle
  • 91. /** * Appelée après le démarrage ou une pause. * Relancez les opérations arrêtées (threads). * Mettez à jour votre application et vérifiez vos écouteurs. */ @Override public void onResume(){ super.onResume(); // Placez votre code ici } Activity lifecycle
  • 92. Activity : declaration  To be usable, an activity must be declared  Inside the AndroidManifest.xml file. … <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=”.ourActivity" android:label="@string/app_name"> </activity> </application> ...
  • 94. Intent  An intent is an abstract description of an operation to be performed.  We can use it to :  Launch an Activity.  Communicate with components like :  Background Services.  Broadcast Receivers.  The first one is the most common usage  We’ll only see it.
  • 95. Intent : Launch an Activity  To simply launch an activity :  One of Instant constructors take only this two parameters :  The context of the intent, here the activity instance creating it.  The component class used for the intent.  startActivity(Intent) :  An instance method of Activity class to start a new activity with an intent. Intent intent = new Intent(this, ActivityToLaunch.class); startActivity(intent);
  • 96. Intent : Important remark Remember : An Activity have to be declared inside Android Manifest file to be launched.
  • 97. Intent : Include extra data  When you launch another activity, you often need to communicate some information.  You can use the intent methods below :  void putExtra(…)  Bundle getExtras(…)  Supported types are :  Primitives : byte, short, int, long, float, double, …  Primitive Arrays : int[], long[], …  Strings  Serializable objects.
  • 98. Intent : include extra data  To put an extra data :  To retrieve it in the launched Activity :  Intent getIntent() :  Return the intent that started this activity. Intent intent = new Intent(this, MyActivity.class); intent.putExtra("smthg", "Hi Activity."); startActivity(intent, MY_ACTIVITY_CODE); Bundle extras = getIntent().getExtras(); if(extras != null) { String message = extras.getString("smthg"); }
  • 100. Persistence: Presentation  Android provide four ways to store data :  Instance State.  Shared Preferences.  SQLite databases.  Files.  We’re going to see the first three.
  • 101. Persistence: Presentation  To put an extra data :  To retrieve it in the launched Activity :  Intent getIntent() :  Return the intent that started this activity. Intent intent = new Intent(this, MyActivity.class); intent.putExtra("smthg", "Hi Activity."); startActivity(intent, MY_ACTIVITY_CODE); Bundle extras = getIntent().getExtras(); if(extras != null) { String message = extras.getString("smthg"); }
  • 102. Persistence: Instance State  You have seen earlier activities life cycle.  A background activity can be unloaded if another one need memory.  How to save activity state to allow user to retrieve his activity as before ?  Thanks to Instance State !  We’re going to see the two activity methods to manage instance state : onSaveInstanceState(…) onRestoreInstanceState(…)
  • 103. Persistence: Instance State  onSaveInstanceState(Bundle)  Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).  onRestoreInstanceState(Bundle)  This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in Bundle type parameter.
  • 104. Persistence: Instance State  By default, Instance State save the values of all views with id attribute.  If you want to save more information, just override the two methods we have just seen. private String myInformation; ... protected void onSaveInstanceState(Bundle outState) { outState.putString("anotherInformation", myInformation); super.onSaveInstanceState(outState); } protected void onRestoreInstanceState(Bundle savedInstanceState){ super.onRestoreInstanceState(savedInstanceState); myInformation = savedInstanceState.getString("anotherInformat ion"); }
  • 105. Persistence: Shared Preferences  Share across all components in an application.  Set of key/value pair.  Can only store boolean, int, long, float and String values.  Permission can be given :  MODE_PRIVATE  Default value, the created file is only accessible by the application that created it.  MODE_WORD_READABLE  Other applications can read the file but not modify it.  MODE_WORD_WRITABLE  Other applications can modify the file.
  • 106. Persistence: Shared Preferences  Examples :  Save shared preferences : SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString(“username”, “Droid”); editor.putBoolean(“isAdmin”, true); editor.commit();
  • 107. Persistence: Shared Preferences  Examples :  Retrieve shared preferences : SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); // If there is no value for “username”, return null String username = prefs.getString(“username”, null); // If there is no value for “isAdmin”, return false boolean admin = prefs.getBoolean(“isAdmin”, false); // If there is no value for “id”, return zero long id = prefs.getLong(“id”, 0L);
  • 108. Persistence: SQLiteDatabases  Relational Database Management System.  Useful to stock complex data.  Each database is dedicated to only one application.  An application can have several databases.  To share data with another application, you can use a Content Provider (out of the course's scope).
  • 109. Persistence: SQLiteDatabases  Don’t design your SQLite database as a MySQL or PostgreSQL ones.  Mobile devices are not dedicated database server  Little storage space.  Little memory.  Store only what you need.  Avoid frequent requests.  Design SQLite databases with :  A simple structure.  Data easily identifiable.  Don’t store binary data !
  • 110. Persistence: SQLiteOpenHelper  To simplify your code to create or update a Database schema, the SDK propose you a Helper class named : SQLiteOpenHelper.  To use it, create your proper class and extend it. Abstract Methods
  • 111. Persistence: SQLiteOpenHelper  Example : public class MyOpenHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = “my.db”; private static final int DATABASE_VERSION = 2; private static final String TABLE_NAME = ”persons"; private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " (" + ”id INTEGER PRIMARY KEY AUTOINCREMENT, " + “name TEXT NOT NULL);"; public MyOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } ...
  • 112. Persistence: SQLiteOpenHelper  Example : ... public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_CREATE); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w("Example", ”Upgrading database, this will drop” + “tables and recreate."); db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } }
  • 113. Persistence: SQLiteDatabase  This class provides two other methods very useful :  SQLiteDatabase getWritableDatabase()  Return a SQLiteDatabase instance to read or write in the Database. Throw an exception if the database cannot be opened for writing (bad permission or full disk).  SQLiteDatabase getReadableDatabase()  Return a SQLiteDatabase instance with read-only access to the database.  Both will create the database if it doesn’t exist.
  • 114. Persistence: SQLiteDatabase  Exposes methods to manage a SQLite database.  Has methods to create, delete, execute SQL commands, and perform other common database management tasks.  We’re going to see some useful methods :  void execSQL(...)  long insert(…)  int update(…)  int delete(…)  Cursor query(…)
  • 115. Persistence: SQLiteDatabase  void execSQL(String sql) :  Execute a single SQL statement that is not a query.  For example, CREATE TABLE, DELETE, INSERT, etc.  Example : SQLiteDatabase db = ... db.execSQL("DROP TABLE IF EXISTS my_table");
  • 116. Persistence: SQLiteDatabase  long insert (String table, String nullColumnHack, ContentValues values) :  Convenience method for inserting a row into the database.  Three parameters :  table : The table to insert the row into.  nullColumnHack :  SQL doesn't allow inserting a completely empty row.  If initialValues is empty this column will explicitly be assigned a NULL value.  values :  Map containing the column values for the row  The keys should be the column names.  The values the column values.
  • 117. Persistence: SQLiteDatabase  long insert (String table, String nullColumnHack, ContentValues values) :  Return the row ID of the inserted row.  Example : SQLiteDatabase db = ... ContentValues values = new ContentValues(); values.put(“name”, “bentahar”); db.insert(“persons”, null, values);
  • 118. Persistence: SQLiteDatabase  int update (String table, ContentValues values, String whereClause, String[] whereArgs) :  Convenience method for updating rows in the database.  Four parameters :  table : the table to update in.  values : a map from column names to new column values.  whereClause : the optional WHERE clause to apply when updating.  whereArgs : an array of the value to apply to the WHERE clause.  Return the number of rows affected.
  • 119. Persistence: SQLiteDatabase  int update (String table, ContentValues values, String whereClause, String[] whereArgs) :  Example : SQLiteDatabase db = ... ContentValues values = new ContentValues(); values.put("name", ”Zakaria"); String[] whereArgs = { "1" }; db.update(“persons”, values, "id=?", whereArgs);
  • 120. Persistence: SQLiteDatabase  int delete (String table, String whereClause, String[] whereArgs) :  Convenience method for deleting rows in the Database.  Three parameters :  table : the table to delete from.  whereClause : the optional WHERE clause to apply when deleting.  whereArgs : an array of the value to apply to the WHERE clause.  Return the number of rows affected.
  • 121. Persistence: SQLiteDatabase  int delete (String table, String whereClause, String[] whereArgs) :  Example : SQLiteDatabase db = ... String[] whereArgs = { "1" }; db.delete("persons", "id=?", whereArgs);
  • 122. Persistence: SQLiteDatabase  Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) :  Query the given table, returning a Cursor over the result set.  Seven parameters :  table : The table name to compile the query.  columns : A list of which columns to return.  selection : A filter declaring which rows to return, formatted as an SQL WHERE clause.
  • 123. Persistence: SQLiteDatabase  Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) :  Seven parameters :  selectionArgs : You may include ?s in selection, which will be replaced by the values from selectionArgs.  groupBy : A filter declaring how to group rows, formatted as an SQL GROUP BY clause.  having : A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause.  orderBy : How to order the rows, formatted as an SQL ORDER BY clause.
  • 124. Persistence: SQLiteDatabase  Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) :  Example : SQLiteDatabase db = ... String[] columns = { ID_COLUMN, NAME_COLUMN }; String[] params = { “Cartman” }; Cursor result = db.query(TABLE_NAME, columns, ”name=?", params, null, null, null, "1");
  • 125. Persistence: Cursor  Provide access to the result set returned by a database query.  Methods commonly used are :  getCount() : returns the number of rows.  moveToFirst() : moves the cursor to the first row.  moveToNext() : moves the cursor to the next line.  isAfterLast() : returns true if the cursor position is after the last row.  getColumnNames() : returns a string array holding the names of all of the columns in the result set.  getColumnIndex(String name) : return the index of the corresponding column name.
  • 126. Persistence: Cursor String[] columns = { “id”, “name”}; Cursor result = db.query(“persons”, columns, null, null, null, null, null); List<Person> persons = new ArrayList<Person>(); result.moveToFirst(); while(!result.isAfterLast()) { Person person = new Person(); person.setId(result.getLong(0)); person.setName(result.getString(1)); persons.add(person); result.moveToNext(); } result.close(); return persons;  Example of use :

Editor's Notes

  1. L'Open Handset Alliance (abrégé OHA) est un consortium de plusieurs entreprises dont le but est de développer des normes ouvertes pour les appareils de téléphonie mobile. Le consortium a été créé le 5 novembre 2007 à l'initiative de Google qui a su fédérer autour de lui 34 compagnies (En 2008. Voir le lien sur les membres actuels). On note ainsi la présence d'opérateurs comme NTT DoCoMo, Sprint Nextel, Telecom Italia ou Bouygues Telecom. Des équipementiers tels que Samsung, Motorola ou LG Electronics. Des semi-conducteurs comme Intel ou Nvidia. Et enfin des incontournables de l'Internet dont eBay. On remarquera quelques grands absents dont Nokia. Et pour cause. Le numéro 1 de la téléphonie mobile possède Symbian, un éditeur de systèmes d'exploitation pour portables. Cependant Nokia ne s'interdit pas d'entrer un jour dans le consortium1. Sur ce nouveau marché, Google viendra également se frotter à la concurrence de Microsoft, qui ne figure pas non plus au sein de l'alliance. L'éditeur a développé un système d'exploitation propriétaire,Windows Mobile, qui équipe plusieurs smartphones comme certains de Qtek, de Motorola ou de Treo.
  2. L'Open Handset Alliance (abrégé OHA) est un consortium de plusieurs entreprises dont le but est de développer des normes ouvertes pour les appareils de téléphonie mobile. Le consortium a été créé le 5 novembre 2007 à l'initiative de Google qui a su fédérer autour de lui 34 compagnies (En 2008. Voir le lien sur les membres actuels). On note ainsi la présence d'opérateurs comme NTT DoCoMo, Sprint Nextel, Telecom Italia ou Bouygues Telecom. Des équipementiers tels que Samsung, Motorola ou LG Electronics. Des semi-conducteurs comme Intel ou Nvidia. Et enfin des incontournables de l'Internet dont eBay. On remarquera quelques grands absents dont Nokia. Et pour cause. Le numéro 1 de la téléphonie mobile possède Symbian, un éditeur de systèmes d'exploitation pour portables. Cependant Nokia ne s'interdit pas d'entrer un jour dans le consortium1. Sur ce nouveau marché, Google viendra également se frotter à la concurrence de Microsoft, qui ne figure pas non plus au sein de l'alliance. L'éditeur a développé un système d'exploitation propriétaire,Windows Mobile, qui équipe plusieurs smartphones comme certains de Qtek, de Motorola ou de Treo.
  3. Android affronte une forte concurrence dans un marché où les solutions logicielles pour appareils mobiles sont nombreuses : Comparer les offres concurrentes à celle d’Android est compliqué tant les stratégies et les approches sont différentes ; certains proposent un système intégré (téléphone + OS), d’autres tentent d’unifier le modèle d’exécution des applications entre les ordinateurs de bureau et les mobiles. Android quant à lui se positionne comme un système d’exploitation et un environnement de développement open source, dédié aux appareils mobiles, et indépendant de toute plateforme matérielle spécifique. iPhone OS : le concurrent numéro un pour Android. Il s’agit bien sûr du système présent sur les différents générations d’iPhone, produits par Apple mais également sur ses tablettes iPad ; Windows Mobile : tout autant propriétaire, le système pour mobiles proposé par Microsoft est distribué sur de nombreux téléphones ; Symbian : récemment passé en open source, ce système d’exploitation est la propriété de Nokia et est présent – entre autres – sur un grand nombre de téléphones de la firme finlandaise ; BlackBerry OS : il est présent sur tous les téléphones de la marque RIM (Research In Motion) ; Palm webOS : le successeur de Palm OS, qui équipe tous les terminaux de la marque éponyme ; LiMo : contraction de « Linux Mobile », LiMo est un système ouvert basé, comme son nom l’indique, sur Linux ; MeeGo : Intel et Nokia ont récemment annoncé la fin du support de Moblin (basée sur un système Linux Fedora) et de Maemo (basée sur un système Linux Debian) en faveur de MeeGo qui vise un marché plus vaste que les téléphones et les netbooks (téléviseurs connectés notamment). Le coeur serait une reprise de Moblin et Qt serait utilisé pour le développement ; et bien d’autres systèmes plus marginaux, souvent développés pour des appareils spécifiques (PDA, etc.).
  4. Le logiciel, qui avait été surnommé gPhone par les rumeurs de marchés, est proposé de façon gratuite et librement modifiable aux fabricants de téléphones mobiles, ce qui facilite son adoption. Le gPhone a été lancé en octobre 2008 aux États-Unis dans un partenariat de distribution exclusif entre Google et T-Mobile. Android (prononcé androïde) est un système d'exploitation open source pour smartphones, PDA et terminaux mobiles conçu par Android, une startup rachetée par Google, et annoncé officiellement le 5 novembre 2007. D'autres types d'appareils possédant ce système d'exploitation existent, par exemple des téléviseurs et des tablettes.
  5. Les différentes versions d'Android ont toutes des noms de desserts (en anglais) depuis la sortie de la version 1.5 et suivent une logique alphabétique Android est disponible en version 2.3. Les versions se succèdent rapidement et les changements qui les accompagnent sont souvent conséquents en termes de nouvelles fonctionnalités et d’améliorations.
  6. Android est conçue pour des appareils mobiles au sens large. Nullement restreinte aux téléphones, elle ouvre d’autres possibilités d’utilisation des tablettes, des ordinateurs portables, des bornes interactives, des baladeurs…
  7. Android est une pile logicielle qui repose sur le couple, en passe de devenir un classique : WebKit est le moteur du navigateur web Média capable d’encoder et de décoder des flux audio et vidéo SQLite est un moteur de base de données sous forme de librairie C et par conséquent destiné exclusivement à être encapsulé dans un logiciel. machine virtuelle a été dénommée Dalvik. Google a fait le choix de s’écarter des standards Java et de proposer sa propre machine virtuelle. Google ne garde de Java que le langage et une partie des API standard et met de côté la plateforme d’exécution (JVM) ; une machine virtuelle dite « registered-based », basée sur les registres, et non pas « stack-based » comme la JVM de Sun. Linux/Java Comme n’importe quel OS, ce noyau a la responsabilité de gérer le matériel à l’aide de drivers, la mémoire, les processus ou encore les couches réseaux basses. Basé sur Linux 2.6.24 Système de fichiers supporté : FAT32 Support de TCP/IP, UDP,… libc (librairie système C standard) dont l’implémentation a été adaptée pour l’occasion à un mode embarqué.
  8. Gen: est un répertoire qui contient une classe R( ressources) qui contient des classes internes, telque chaque classe représente un répertoire dans RES; Exemple: le répertoire Drawable contient des images, alors dans un la classe R.java il y a une classe interne Drawable tq les membres de cette classe sont les id de chaque image contenu dans ce répertoire (Drawable). Ainsi par la suite, on verra que l’accès à ces ressources sera un accès à leur identifiant généré dans cette classe et non diréctement, chose qui donne au programme une souplesse et une rapidité d’accès aux ressources. Assets contient simplement des données qui seront chargées sur le mobile lors de la compilation de votre projet. Les données inclues dans ce dossier ne sont normalement pas en accord avec l’arborescence classique d’un projet Android : cela peut, par exemple, être des fichiers texte décrivant la license de votre application, des fichiers audio ou vidéo, etc. Ils ne seront pas compilées !!! Res/Values values : ce dossier contient également un ensemble de fichiers décrivant les valeurs utilisées par votre application. On peut, par exemple, y mettre des chaines de caractères (strings.xml), des tableaux (arrays.xml), des couleurs, des dimensions, etc. AndroidManifest définit le comportement de votre application au système Android. Ce fichier définit par exemple, le nom, l’icone (par défaut drawable/icon.png), le thème, la version minimale du système nécessaire à l’exécution de l’application, les activités, les services, etc. de votre application. default.properties Fichier de propriétés utilisé pour la compilation. proguard.cfg ProGuard est un outil qui optimise et obscurcit votre code en supprimant le code inutilisé et en renommant des classes, des champs et des méthodes avec des noms sémantiquement obscures.  Le résultat est un fichier de plus petite taille apk. qui est plus difficile à appliquer sur lui le reverse engineer. RES Afin de simplifier la façon dont les développeurs de concevoir leurs interfaces utilisateurs pour de multiples appareils et dispositifs pour permettre à plus de participer sans affecter les applications, la plate-forme divise la gamme de tailles d'écran réels pris en charge et les résolutions en: Un ensemble de quatre tailles généralisée:petites, normales, grandes et xlarge Un ensemble de quatre densités généralisées:LDPI (basse), MDPI (moyen), hdpi (élevé), etxhdpi (très haute) res / layout / my_layout.xml / / mise en page pour la taille de l'écran normal res / layout-petits / my_layout.xml / / mise en page pour petitesse de l'écran res / schéma de gros / my_layout.xml / / mise en page pour écran de grande taille res / layout-grand-terrain / my_layout.xml / / mise en page pour grand écran en mode paysage res / layout-xlarge / my_layout.xml / / mise en page pour la taille de l'écran extra large res / étirable-lhdpi / my_icon.png / / image pour une faible densité res / étirable-MDPI / dpi / my_icon.png / / image pour la densité moyenne res / étirable-hdpi / my_icon.png / / image à haute densité res / drawable-nodpi / composite.xml / ressources / densité indépendante