Tutoriel Android Communication entre services BroadCast Receiver Romain Raveaux

Documents pareils
Android Publish/Subscribe, GCM, Google Cloud Messaging : une introduction

TP SIN Programmation sur androïde Support : eclipse

Projet Android (LI260) Cours 2

SOMMAIRE

TP au menu «UI ANDROID»

Développement sous Android

Warren PAULUS. Android SDK et Android x86

Tutorial pour une application simple

Créer des applications Android

Android et le Cloud Computing

Programmation des applications mobiles avec Android. 1 Inspiré du cours de Olivier Le Goaer

Les fondamentaux du développement d applications Java

Les connexions sans fil avec Android. JMF (Tous droits réservés) 1

Projet de programmation (IK3) : TP n 1 Correction

Outils, langage et approche Android Une introduction. Nicolas Stouls lyon.fr

Programmation Mobile Android Master CCI

Page 1 sur 5 TP3. Thèmes du TP : l la classe Object. l Vector<T> l tutorial Interfaces. l Stack<T>

Package Java.util Classe générique

Remote Method Invocation (RMI)

RMI le langage Java XII-1 JMF

IFT287 Exploitation de base de données relationnelles et orientées objet. Laboratoire Mon premier programme Java en Eclipse

Auto-évaluation Programmation en Java

Initiation à JAVA et à la programmation objet.

Corrigé des exercices sur les références

Environnements de développement (intégrés)

TD/TP PAC - Programmation n 3

Serveur d'archivage 2007 Installation et utilisation de la BD exist

Android UIThread, Thread, Handler et AsyncTask

De Java à Android version 0.1

Education Delivery Intelligent Tool

Module Architecture des systèmes mobiles : Android première partie Didier FERMENT - UPJV

Structure d un programme et Compilation Notions de classe et d objet Syntaxe

Programmation Android L3 informatique

Programmation par les Objets en Java

TD/TP PAC - Programmation n 3

Java Licence Professionnelle CISII,

Tp 1 correction. Structures de données (IF2)

Langage et Concepts de Programmation Objet. 1 Attributs et Méthodes d instance ou de classe. Travaux Dirigés no2

Programme Compte bancaire (code)

LMI 2. Programmation Orientée Objet POO - Cours 9. Said Jabbour. jabbour@cril.univ-artois.fr

J2SE Threads, 1ère partie Principe Cycle de vie Création Synchronisation

TD Objets distribués n 3 : Windows XP et Visual Studio.NET. Introduction à.net Remoting

Tutoriel Android. Pour démarrer la programmation d'applications Android

Cours 1: Java et les objets

Programmation Réseau. Sécurité Java. UFR Informatique jeudi 4 avril 13

République Algérienne Démocratique et Populaire Université Abou Bakr Belkaid Tlemcen Faculté des Sciences Département d Informatique

Introduction ANDROID

La persistance des données dans les applications : DAO, JPA, Hibernate... COMPIL 2010 francois.jannin@inp-toulouse.fr 1

Serveur d'application Client HTML/JS. Apache Thrift Bootcamp

JADE : Java Agent DEvelopment framework. Laboratoire IBISC & Départ. GEII Université & IUT d Evry nadia.abchiche@ibisc.univ-evry.

Lambda! Rémi Forax Univ Paris-Est Marne-la-Vallée

APPLICATIONS JAVA. 1. Android. Développement d'activités Java sous Android. Android Partie I. L'architecture du système Android. Application Android

Remote Method Invocation Les classes implémentant Serializable

Java Licence Professionnelle Cours 7 : Classes et méthodes abstraites

Synchro et Threads Java TM

Développement sous Android

Android en action. Abdelkader Lahmadi Université de Lorraine

DÉVELOPPEMENT ANDROID

Pour signifier qu'une classe fille hérite d'une classe mère, on utilise le mot clé extends class fille extends mère

Exceptions. 1 Entrées/sorties. Objectif. Manipuler les exceptions ;

Programmer en JAVA. par Tama

RMI. Remote Method Invocation: permet d'invoquer des méthodes d'objets distants.

F. Barthélemy. 17 mai 2005

La base de données XML exist. A. Belaïd

TP1. Outils Java Eléments de correction

TD3: tableaux avancées, première classe et chaînes

Un ordonnanceur stupide

Architectures Mobiles

Objets et Programmation. origine des langages orientés-objet

Par Laurent DESECHALLIERS. Mastère Spécialisé en Management de Projets en Milieu Industriel. CESI de Rouen Promotion 2002/2003.

API04 Contribution. Apache Hadoop: Présentation et application dans le domaine des Data Warehouses. Introduction. Architecture

Plan du cours. Historique du langage Nouveautés de Java 7

Cours Android. Développement et API. Romain Raveaux 1. Mars 06-03, romain.raveaux at univ-tours.fr. Organisation du module

Premiers Pas en Programmation Objet : les Classes et les Objets

TD2 Programmation concurrentielle

[APPLICATON REPARTIE DE VENTE AUX ENCHERES]

Info0604 Programmation multi-threadée. Cours 5. Programmation multi-threadée en Java

Terminaux Mobiles Communicants

TP3. Mail. Attention aux fausses manoeuvres lors de ce TP vous pouvez endommager votre mail sur ouindose.

Tutoriel Android - TP de prise en main

Encore plus de widgets et de conteneurs

SYNC FRAMEWORK AVEC SQLITE POUR APPLICATIONS WINDOWS STORE (WINRT) ET WINDOWS PHONE 8

Encapsulation. L'encapsulation consiste à rendre les membres d'un objet plus ou moins visibles pour les autres objets.

Intégration d'un système d'audio-vidéo conférence sur un robot de téléprésence

Calcul Parallèle. Cours 5 - JAVA RMI

Héritage presque multiple en Java (1/2)

Introduction à Java. Matthieu Herrb CNRS-LAAS. Mars

Derrière toi Une machine virtuelle!

TP1 : Initiation à Java et Eclipse

Corrigés des premiers exercices sur les classes

as Architecture des Systèmes d Information

Java Licence professionnelle CISII,

INITIATION AU LANGAGE JAVA

Développement web et mobile

Design patterns. Design patterns - définition. Design patterns - avantages

1.3 Gestion d'une application

P r ob lé m a t iq u e d e la g é n é r icit é. Pr in cip e d e la g é n é r icit é e n Ja v a ( 1 /3 )

Création d un service web avec NetBeans 5.5 et SJAS 9

Dis papa, c est quoi un bus logiciel réparti?

Développement Logiciel

Transcription:

Tutoriel Android Communication entre services BroadCast Receiver Romain Raveaux Préambule... 1 Prérequis... 2 Architecture... 3 Envoi d un message au ServiceS1... 5 Mise en œuvre... 6 Modification du Manifest... 7 Les classes du tutorial... 8 Classe ServiceS1... 9 Classe ServiceS2... 11 Classe TutoActivity... 13 Manifest de l application... 15 Préambule Les services ne peuvent pas communiquer par le biais de l interface «IBinder». La communication par IBinder ne permet que la communication entre une Activity et un service. La solution pour résoudre le problème est d utiliser les BroadCast Receiver Service S1 message Service S2 1

Prérequis Savoir démarrer et arrêter un service. Savoir créer une application Android. 2

Architecture On crée un service «ServiceS1» avec deux variables : Une donnée à envoyer et une variable pour recevoir un message. public class ServiceS1 extends Service { String datatosend ="ping"; String receiveddata; public IBinder onbind(intent arg0) { return null; /** * @param args */ public static void main(string[] args) { A l intérieur de la classe «ServiceS1», on crée une classe BroadCastReceiver. public class S1Receiver extends BroadcastReceiver { public void onreceive(context context, Intent arg1) { Toast.makeText(context, "reçu!!!",toast.length_long ).show(); Log.d(this.getClass().getName(), "reçu!!!"); receiveddata = arg1.getextras().getstring("id"); Toast.makeText(context, receiveddata,toast.length_long ).show(); 3

On crée le constructeur du service «ServiceS1». La variable messagereceiver est une instance de S1Receiver. Il faut enregistrer le S1Receiver pour avertir l application que le service ServiceS1 possède un BroadCast Receiver qui pourra être appelé par d autres services. MESSAGE_S1 est l identifiant du BroadCast Receiver S1Receiver. S1Receiver messagereceiver; public static String MESSAGE_S1 = "MESSAGE_S1"; public ServiceS1(){ super() ; messagereceiver = new S1Receiver(); registerreceiver(messagereceiver, new IntentFilter(MESSAGE_S1)); 4

Envoi d un message au ServiceS1 Pour illustrer la communication entre deux services, nous avons besoin de deux services. On crée un autre service «ServiceS2». public class ServiceS2 extends Service { String datatosend ="pong"; String receiveddata; public IBinder onbind(intent arg0) { return null; /** * @param args */ public static void main(string[] args) { Lors du démarrage du service S2, ce dernier enverra un message au service S1. Le service S2 envoie par le biais de la méthode sendbroadcast un Intent contenant la variable datatosend. Intent sender = new Intent(ServiceS1.MESSAGE_S1); sender.putextra("id", datatosend); sendbroadcast(sender); 5

Mise en œuvre Les services s exécutent en tâche de fond de manière parallèle. Démarrage de l activité Démarrage du service S1 Mise en place du BroadCast Receiver Démarrage du service S2 Envoi du message a S1 Réception du message temps Pour expérimenter notre communication entre services nous avons besoin d une activité avec un bouton permettant de démarrer les services. 6

Voici le code de la méthode «oncreate» de l activité. Lors de l appuie sur un bouton, on démarre le service S1 et le service S2. public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.tutolayout); start = (Button) this.findviewbyid(r.id.button1); start.setonclicklistener(new Button.OnClickListener(){ public void onclick(view v) { Intent starter = new Intent(TutoActivity.this,ServiceS1.class); startservice(starter); starter = new Intent(TutoActivity.this,ServiceS2.class); startservice(starter); ); Modification du Manifest Dans le manifest de l application, il faut rajouter la déclaration des services entre les balises «application». <service android:name=".services.services1" /> <service android:name=".services.services2" /> 7

Les classes du tutorial 8

Classe ServiceS1 package com.example.carteauxtresors.services; import com.example.carteauxtresors.services.ordonnanceur.myreceiver; import android.app.service; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.ibinder; import android.util.log; import android.widget.toast; public class ServiceS1 extends Service { String datatosend ="ping"; String receiveddata; S1Receiver messagereceiver; public static String MESSAGE_S1 = "MESSAGE_S1"; public ServiceS1(){ super(); public int onstartcommand(intent intent, int flags, int startid) { Log.d(this.getClass().getName(), "onstart"); Log.d("LocalService", "Received start id " + startid + ": " + intent); messagereceiver = new S1Receiver(); registerreceiver(messagereceiver, new IntentFilter(MESSAGE_S1)); return START_NOT_STICKY; public IBinder onbind(intent arg0) { // TODO Auto- generated method stub return null; /** * @param args */ public static void main(string[] args) { 9

// TODO Auto- generated method stub public class S1Receiver extends BroadcastReceiver { public void onreceive(context context, Intent arg1) { // TODO Auto- generated method stub Toast.makeText(context, "S1 reçu!!!",toast.length_long ).show(); Log.d(this.getClass().getName(), "S1 reçu!!!"); receiveddata = arg1.getextras().getstring("id"); Toast.makeText(context, receiveddata,toast.length_long ).show(); public void ondestroy() { Log.d(this.getClass().getName(), "ondestroy"); unregisterreceiver(messagereceiver); 10

Classe ServiceS2 package com.example.carteauxtresors.services; import android.app.service; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.os.ibinder; import android.util.log; import android.widget.toast; public class ServiceS2 extends Service { String datatosend ="pong"; String receiveddata; public ServiceS2(){ super(); public int onstartcommand(intent intent, int flags, int startid) { Log.d(this.getClass().getName(), "onstart"); Log.d("LocalService", "Received start id " + startid + ": " + intent); Intent sender = new Intent(ServiceS1.MESSAGE_S1); sender.putextra("id", datatosend); sendbroadcast(sender); return START_NOT_STICKY; public IBinder onbind(intent arg0) { return null; /** * @param args */ public static void main(string[] args) { 11

public void ondestroy() { Log.d(this.getClass().getName(), "ondestroy"); 12

Classe TutoActivity package com.example.carteauxtresors; import com.example.carteauxtresors.services.ordonnanceur; import com.example.carteauxtresors.services.services1; import com.example.carteauxtresors.services.services2; import android.app.activity; import android.content.intent; import android.os.bundle; import android.view.view; import android.widget.button; public class TutoActivity extends Activity { /** * @param args */ public static void main(string[] args) { private Button start; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.tutolayout); start = (Button) this.findviewbyid(r.id.button1); start.setonclicklistener(new Button.OnClickListener(){ public void onclick(view v) { Intent starter = new Intent(TutoActivity.this,ServiceS1.class); startservice(starter); starter = new Intent(TutoActivity.this,ServiceS2.class); startservice(starter); 13

); 14

Manifest de l application <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.carteauxtresors" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".tutoactivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <service android:name=".services.services1" /> <service android:name=".services.services2" /> </application> </manifest> 15