43
POO 2014-2015 Pour compléter l’introduction

Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Pour compléter l’introduction

Page 2: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 02 / 43

• Liens avec le TP03 - Android

• Ajouts

• Retirer

• Par FragmentTransaction (et commit)

• Déplacement par tri des View générées

Fragment Menu Intent AsyncTask

Page 3: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 03 / 43

• Il s’agit de déplacer la vue liée au fragment

• Il faut donc le retrouver dans son parent, et le changer d’indice

– Boucle for…

– Car il manque :

private View[] getChilds(ViewGroup v) {

View [] res = null;

if (v != null) {

res = new View[v.getChildCount()];

for(int i = 0; i < res.length; i++) res[i] = v.getChildAt(i);

}

return res;

}

• Pour changer l’indice, c’est la méthode <ViewGroup>.addView( v, i)… mais avant il faut l’enlever

Fragment Menu Intent AsyncTask

Page 4: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 04 / 43

• Caution: ”Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).”http://developer.android.com/training/basics/activity-lifecycle/recreating.html

• Re-créer => refaire des objets…• Pour les fragments, on s’en sort car il y a le paramètres (et recréer avec ce même

paramètre)• Des fonctions peuvent être appelées avant destruction

– onSaveInstanceState pour une Activité– onSaveInstanceState pour un fragment– on peut y remplir le bundle– Ne pas oublier l’appel à super.xxx

• Méthode pour utiliser ce qui est sauvé– onCreate(Bundle saved) pour un fragment– onRestoreInstanceState(Bundle inState) pour une activité

• A faire évoluer… en même temps que le code…

Fragment Menu Intent AsyncTask

Page 5: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 05 / 43

• Comme un fragment…

– Un peu particulier (dialog)

– Méthode show, pas de transaction

• Besoin de prévoir la communication (interface logicielle), notamment pour la valeur de retour

Fragment Menu Intent AsyncTask

Page 6: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 06 / 43

• Le tri des tâches : – Comparable de java

– Enum de java

• C.f. cours POO s5…

• Puis gestion de la rotation (re remplir la liste de fragment, à partir de leur onCreate par un appel à leur activité)

Fragment Menu Intent AsyncTask

Page 7: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 07 / 43

• Source de l’image : « android programming, the big nerd ranch guide »

Fragment Menu Intent AsyncTask

Page 8: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 08 / 43

• Appel Méthode setRetainInstance(true) dans onCreate du Fragment

android programming, the big nerd ranch guideFragment Menu Intent AsyncTask

Page 9: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 09 / 43

• L’attribut android:name attribute indique la classe qui extends Fragment

• Insertion de la Viewretournéepar onCreateView()

• Note: chaque fragment nécessite un id (ou tag) – Meilleur gestion par Android

– android:id attribute (unique)

– android:tag avec une string unique

– Les deux

Une View “fragment”

<fragmentandroid:name=“nom_complet_classe"android:id="@+id/le_id"etc.

" />

Fragment Menu Intent AsyncTask

Page 10: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 10 / 43

• Comme un fragment…

– Un peu particulier (dialog)

– Méthode show, pas de transaction

• Besoin de prévoir la communication (interface logicielle), notamment pour la valeur de retour

Fragment Menu Intent AsyncTask

Page 11: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 11 / 43

Fragment Menu Intent AsyncTask

Page 12: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 12 / 43

• Dossier menu dans res<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<itemandroid:id="@+id/tri_buttoir"android:orderInCategory="100"android:showAsAction="never"

android:title="@string/tri_buttoir"/>

<itemandroid:id="@+id/tri_creation"android:orderInCategory="100"android:showAsAction="never"

android:title="@string/tri_creation"/></menu>

Fragment Menu Intent AsyncTask

Page 13: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 13 / 43

• <menu>Defines a Menu, which is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and <group> elements.

• <item>Creates a MenuItem, which represents a single item in a menu. This element may contain a nested<menu> element in order to create a submenu.

• <group>An optional, invisible container for <item> elements. It allows you to categorize menu items so they share properties such as active state and visibility. For more information, see the section about Creating Menu Groups.

• Pour la balise item :• android:id

A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it.

• android:iconA reference to a drawable to use as the item's icon.

• android:titleA reference to a string to use as the item's title.

• android:showAsActionSpecifies when and how this item should appear as an action item in the action bar.

http://developer.android.com/guide/topics/ui/menus.htmlFragment Menu Intent AsyncTask

Page 14: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 14 / 43

• Méthode pour la création dans une Activity@Overridepublic boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.nom_du_fichier_xml,

menu);return true;

}

Fragment Menu Intent AsyncTask

Page 15: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 15 / 43

• Toujours dans une Activity@Overridepublic boolean onOptionsItemSelected(MenuItem item) {

// Handle item selectionswitch (item.getItemId()) {

case R.id.un_id:// des actions…return true;

case R.id.un_autre_id:// des actions en réponse à cet item làreturn true;

// et ainsi de suitedefault:

return super.onOptionsItemSelected(item);}

}

Fragment Menu Intent AsyncTask

Page 16: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 16 / 43

• Le tri des tâches :

– Comparable de java

– Enum de java

• C.f. cours POO s5…

• Puis gestion de la rotation (re remplir la liste de fragment, à partir de leur onCreatepar un appel à leur activité)

// pour alterner les tris

ComparerDate dernierTri = null;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.tri_buttoir:

if ((dernierTri != null) && (dernierTri.equals(ComparerDate.BUTTOIR_CROISSANT))) dernierTri = ComparerDate.BUTTOIR_DECROISSANT;

else dernierTri = ComparerDate.BUTTOIR_CROISSANT;

break;

case R.id.tri_creation:

if ((dernierTri != null) && (dernierTri.equals(ComparerDate.CREATION_CROISSANT))) dernierTri = ComparerDate.CREATION_DECROISSANT;

else dernierTri = ComparerDate.CREATION_CROISSANT;

break;

default:

return super.onOptionsItemSelected(item);

}

trier(dernierTri);

return true; }

Fragment Menu Intent AsyncTask

Page 17: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 17 / 43

Via un autre exemple (fisheye) sur le menu :

V1 : pas de menu

V2 : un menu « simple »

V3 : aller dans une activité fille

V4 : utiliser une activité (Intent) prédéfini

Fragment Menu Intent AsyncTask

Page 18: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 18 / 43

• Fisheye, exemple de personnalisation d’une View– Intégration dans le xml

<fisheye.four.image.DeformablePolygons [...] />

– Surcharge de onDraw, utilisation de Paint

• Mise en place d’un menu « simple »– inflate du menu dans

onCreateOptionsMenu– onOptionsItemSelected pour

réagir aux actions– Utilisation de invalidate() sur la

vue pour la mettre à jouir

Fragment Menu Intent AsyncTask

Page 19: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 19 / 43

• Autre écran = autre activité• Attention au cycle de vie (détruit, pas détruit ?)

• Création d’une autre activité• Déclaration dans le manifest (après l’activité principale)<activity

android:name="fisheye.four.SettingsActivity"android:label="@string/title_activity_settings“android:parentActivityName="fisheye.four.Fisheye">

<meta-dataandroid:name="android.support.PARENT_ACTIVITY"android:value="fisheye.four.Fisheye" />

</activity>

Fragment Menu Intent AsyncTask

Page 20: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 20 / 43

• Méthode simple : startActivity(Intent i) dans Activity

• Intent– Objet de communication avec l’OS

– Dans ce cas, constructeur new Intent(Context, Class)• Context = activité qui lance

• Class = le type de l’activité à lancer

– putExtra pour ajouter des données

• Dans le onCreate de la nouvelle activité– getIntent( )

– getIntent().getIntExtra(“clef", val_defaut);

Fragment Menu Intent AsyncTask

Page 21: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 21 / 43

• Lancement avec startActivityForResult• Méthode setResult(code, intent)

– Avec un code de retour– Avec un Intent (et des extra)

• Méthode de retour dans l’activité qui a lancé

protected void onActivityResult(int requestcode, intresultcode, Intent data) {

if (data == null) return ;Date d = (Date)

data.getSerializableExtra("date");// etc.

}

Fragment Menu Intent AsyncTask

Page 22: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 22 / 43

android programming, the big nerd ranch guide

APPLI

Extra, etc.

Activité A

Activité B

Extra, etc.

Fragment Menu Intent AsyncTask

Page 23: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 23 / 43

Affichage du bouton (dans la barre)if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

getActionBar().setDisplayHomeAsUpEnabled(true);

}

Récupérer l’eventpublic boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case android.R.id.home: // etc. } return true; }

Fragment Menu Intent AsyncTask

Page 24: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 24 / 43

• Appel à setResults

– Faire l’Intent de retour (putExtra pour les valeurs de retour)

– Quitter la vue avec finish

• Pas dans l’esprit

• Mais l’avantage de conserver l’instance de l’activité…

• Utilisation du « up »

– L’activité de départ repart quasiment de zéro

– Perte du onActivityResult

Fragment Menu Intent AsyncTask

Page 25: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 25 / 43

Voir : https://speakerdeck.com/jgilfelt/this-way-up-implementing-effective-navigation-on-android

// pour « relancer » l’activité parent

Intent up = NavUtils.getParentActivityIntent(this);

// éventuellement des valeurs de retours comme extra

up.putExtra(...);

// retour à l’activité, qui repasse par onCreate, mais qui

// n’a pas été tuée (pas de onRestoreInstanceState)

NavUtils.navigateUpTo(this,up);

// s’il n’y a pas de paramètre

// NavUtils.navigateUpFromSameTask(this);

Fragment Menu Intent AsyncTask

Page 26: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 26 / 43

• http://developer.android.com/training/implementing-navigation/ancestral.html

if (NavUtils.shouldUpRecreateTask(this, up)) {// This activity is NOT part of this app's task, so create a new

task// when navigating up, with a synthesized back stack.TaskStackBuilder.create(this)

// Add all of this activity's parents to the back stack.addNextIntentWithParentStack(up)// Navigate up to the closest parent.startActivities();

} else {// This activity is part of this app's task, so simply// navigate up to the logical parent activity.NavUtils.navigateUpTo(this, up);

}

Fragment Menu Intent AsyncTask

Page 27: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 27 / 43

• Pour « tuer »– « Normalement réserver à l’OS »– finish() (+System.exit(0) )– Etc.

• Pour relancer l’application au début à partir de là ou on est :– Dans le manifest, pour L’activité ciblée

android:launchMode="singleTop“– Depuis l’endroit où on veut revenir « au début »Intent intent = new Intent(this, LActivitéPrincipale.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);

Fragment Menu Intent AsyncTask

Page 28: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 28 / 43

• Reconnaissance de parole de google

• Intégrée à Android

private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

/**

* Fire an intent to start the speech recognition activity.

*/

@Override

public void onClick(View v) {

// lancement de l'intent avec le nom de la classe... (constante)

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

// paramètre requis pour interprétation du résultat...

intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,

RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

// titre

intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Fisheye - Speech recognition");

// VOICE_RECOGNITION_REQUEST_CODE pour retrouver l'appel pour le résultat

// nombre choisi par le développeur

startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

}

Fragment Menu Intent AsyncTask

Page 29: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 29 / 43

protected void onActivityResult(int requestcode, int resultcode, Intent data) {// test si le retour est ok et si le retours vient bien de le reco vocale

if (requestcode == VOICE_RECOGNITION_REQUEST_CODE && resultcode == RESULT_OK) {

ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

// […]}else {// un autre cas…}

}

Fragment Menu Intent AsyncTask

Page 30: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 30 / 43

Utilisation de « worker » (AsyncTask)

Exemple : adresse vers coordonnées (nominatim) puis image (openstreetmap)

V1 : l’intention, qui ne fonctionne pas

V2 : une AsyncTask pour l’adresse

V3 : évolution pour charger aussi l’image

Fragment Menu Intent AsyncTask

Page 31: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 31 / 43

• Classes fourni dans java.net

URL siteUrl = new URL(url);

URLConnection conn = siteUrl.openConnection();

// on peut vouloir suivre les redirections…

// HttpURLConnection.setFollowRedirects(true);

// ensuite on a l’InputStream… conn.getInputStream()

// à encapsuler selon ce qu’on reçoit

// par exemple du JSON / text / etc.

BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream(), "UTF-8"));

// lecture tant qu’il y a à lire

while ((line = in.readLine()) != null) { file += line; }

// à la fin, file (une String) contient le fichier distant

in.close();

• Alternative : package d’apache intégré dans android

– http://developer.android.com/reference/org/apache/http/package-summary.html

– package org.apache.http

Fragment Menu Intent AsyncTask

Page 32: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 32 / 43

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="adresseverscoordonnees.three"android:versionCode="1"android:versionName="1.0" >

<uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.INTERNET" />

<application …

Fragment Menu Intent AsyncTask

Page 33: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 33 / 43

• Il faut le « parser »– http://developer.android.com/reference/org/json/package-summary.html

// on reçoit un json qui contient un tableau d’objetJSONArray fileJson= new JSONArray(file);

// si le tableau n’est pas videif ((fileJson != null) && (fileJson.length() > 0)) {

// on prend le premier élément, qui est supposé être un objet

JSONObject adresseRetournee = (JSONObject) fileJson.get(0);result = new Object[2];// on retrouve la propriété « lat » de cette objetresult[0] = (String) adresseRetournee.get("lat") ;// etc.

}

Fragment Menu Intent AsyncTask

Page 34: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 34 / 43

• Impossible à savoir…

• Risque de figer l’interface graphique (et l’application)…

• … mais de toutes façons, depuis 3.x, il est interdit de faire certaines choses dans le thread graphique…

• Donc, il faut faire autrement– Il faut un thread,

– qui puisse faire des choses dans le graphique, plus facilement que la méthode runOnUiThread(Runnable) de la classe Activity

– bref qui ressemble aux (Swing)Worker

Fragment Menu Intent AsyncTask

Page 35: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 35 / 43

• http://developer.android.com/reference/android/os/AsyncTask.html

• AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

• AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.)

• If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge

Fragment Menu Intent AsyncTask

Page 36: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 36 / 43

• An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

• An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps

Fragment Menu Intent AsyncTask

Page 37: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 37 / 43

public class Tache extends AsyncTask<String, String, Object[]> {

// [...] // attributs de la classe

public Tache(TextView lat, TextView lon, ImageView img) {

// constructeur pour obtenir des élémentts

// par exemple graphique, pour mise à jour...

}

@Override

protected Object[] doInBackground(String... params) { // lancer par execute()

// tester les paramètres

if ((params == null)|| (params.length != 2)) return null;

Object [] result = null;

String url = params[0];

// [...] // utilise publishProgress(“<string>");

return result;

}

@Override

protected void onProgressUpdate(String... result){

// [...] // pour montrer la progression // appelé par publishProgress

}

@Override

protected void onPostExecute(Object [] res){

// traitement des résultats... // [...] // appelé à la fin de doInBackground

}

}

Fragment Menu Intent AsyncTask

Page 38: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 38 / 43

• Création (new)• Appel à execute()

1. onPreExecute(), invoked on the UI thread before the task is executed. Setup / Graphical initialization (progress bar)

2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute()This step is used to perform background computation that can take a long time. The result of the computation must be returned by this step and will be passed back to the last step.

3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...) from doInBackground. The timing of the execution is undefined. For user feedback.

4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Fragment Menu Intent AsyncTask

Page 39: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 39 / 43

• Cancel : cancel(boolean). – isCancelled() return true. – onCancelled(Object) instead of onPostExecute– checking isCancelled() periodically in

doInBackground(Object[])

• The AsyncTask class must be loaded on the UI thread. • The task instance must be created on the UI thread.• execute(Params...) must be invoked on the UI thread.• Do not call onPreExecute, onPostExecute,

doInBackground, onProgressUpdate manually.• The task can be executed only once

Fragment Menu Intent AsyncTask

Page 40: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 40 / 43

• Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

• If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Exec

utor, Object[]) withTHREAD_POOL_EXECUTOR.

Fragment Menu Intent AsyncTask

Page 41: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 41 / 43

• Similaire à java

– http://developer.android.com/guide/components/processes-and-threads.html

– Pensez à onResume / onPause et onRestart / onStop, etc.

• Ou lié à des services

– http://developer.android.com/guide/components/services.html

Fragment Menu Intent AsyncTask

Page 42: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 42 / 43

• Tache a besoin

– D’éléments graphiques pour les mettre à jour

– D’une url, d’un message par défaut

• Tache retourne

– Des coordonnées (latitude, longitude)

– Une image (enfin, si c’est ok)

• Publication de l’avancement : du texte

Fragment Menu Intent AsyncTask

Page 43: Pour ompléter l’introdutiondeptinfo.unice.fr/~renevier/ancien/POO-2015/cours/03...2014-2015 Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6,

PO

O 2

01

4-2

01

5

Philippe Renevier Gonin - L3 Informatique Parcours Miage - POO - Android - Semestre 6, 2014-2015 43 / 43

• On recherche un json

– C.f; exemple ci-dessus

• On recherche une image

– Création d’une Bitmap à partir d’un InputStream

• Pour les résultats

– Appels à des setters

– Mise à jour avec invalidate( )

– Masquer / montrer l’image

Fragment Menu Intent AsyncTask