Android Cupcake 1.5 : Réaliser son widget
Par Adrien le jeudi 7 mai 2009, 11:15 - Tutorial - Lien permanent
Bonjour, depuis la sortie du dernier framework, une nouvelle possibilité
réclamée depuis longtemps est apparue : la possibilité de faire vos propres
widgets et de les ajouter sur votre home. Nous allons voir dans les grandes
lignes ce qu'il faut faire, les limitations, et vous retrouverez en pièce
jointe un widget HelloWorld déjà fait.


Les éléments importants :
Dans AndroidManifest.xml :
<receiver android:name=".MonWidget" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget" />
</receiver>
Il faut récupérer l'action APPWIDGET_UPDATE, et signaler la position d'un fichier xml qui décrit le widget, ici le fichier xml/widget.xml :
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dip" android:minHeight="72dip"
android:updatePeriodMillis="2000" android:initialLayout="@layout/widget_layout" />
Il spécifie une taille minimale pour le widget. Pour obtenir la taille, mutipliez le nombre de cases voulues par 74 dip, puis enlevez 2 dip. Il faut également spécifier la période de mise à jour du widget, vous devriez garder cette valeur la plus haute possible pour réduire la consommation de votre widget, n'utilisez de faibles valeurs que pour le dev. Il faut également spécifier un layout initial pour notre widget, il s'agit d'un layout standard comme tout layout xml d'android, mais il subit les limitations que nous verrons plus bas.
Et enfin la classe MonWidget :
public class MonWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text, "Bonjour, Android");
ComponentName thisWidget = new ComponentName(context, MonWidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
}
}
Cette classe hérite AppWidgetProvider, la nouvelle classe du 1.5 qui est dédiée à la création de widget. Pour faire des actions à chaque update, il faut surcharger la méthode onUpdate et récupérer une RemoteViews de la manière ci-dessus.
Cependant, les widgets souffrent de limitations : la manipulation des vues doit se faire à travers le XML, et vous êtes obligés d'utiliser uniquement des vues de la liste suivante, sans possibilité d'y ajouter les vôtres :
AbsoluteLayout AnalogClock Button Chronometer FrameLayout ImageButton ImageView LinearLayout ProgressBar RelativeLayout TextView
De plus, la manipulation de RemoteViews offre assez peu de possibilités, il ne sera donc même pas possible d'utiliser toutes les fonctionnalités des vues autorisées (particulièrement au niveau de la détection de touches / pressions).
Les widgets sont donc de bons moyens de réaliser des agrégateurs de contenus, mais fabriquer un petit gadget interactif (du type xEyes par exemple) est pour l'instant impossible compte tenu des restrictions de sécurité.
Dans AndroidManifest.xml :
<receiver android:name=".MonWidget" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget" />
</receiver>
Il faut récupérer l'action APPWIDGET_UPDATE, et signaler la position d'un fichier xml qui décrit le widget, ici le fichier xml/widget.xml :
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dip" android:minHeight="72dip"
android:updatePeriodMillis="2000" android:initialLayout="@layout/widget_layout" />
Il spécifie une taille minimale pour le widget. Pour obtenir la taille, mutipliez le nombre de cases voulues par 74 dip, puis enlevez 2 dip. Il faut également spécifier la période de mise à jour du widget, vous devriez garder cette valeur la plus haute possible pour réduire la consommation de votre widget, n'utilisez de faibles valeurs que pour le dev. Il faut également spécifier un layout initial pour notre widget, il s'agit d'un layout standard comme tout layout xml d'android, mais il subit les limitations que nous verrons plus bas.
Et enfin la classe MonWidget :
public class MonWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text, "Bonjour, Android");
ComponentName thisWidget = new ComponentName(context, MonWidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
}
}
Cette classe hérite AppWidgetProvider, la nouvelle classe du 1.5 qui est dédiée à la création de widget. Pour faire des actions à chaque update, il faut surcharger la méthode onUpdate et récupérer une RemoteViews de la manière ci-dessus.
Cependant, les widgets souffrent de limitations : la manipulation des vues doit se faire à travers le XML, et vous êtes obligés d'utiliser uniquement des vues de la liste suivante, sans possibilité d'y ajouter les vôtres :
AbsoluteLayout AnalogClock Button Chronometer FrameLayout ImageButton ImageView LinearLayout ProgressBar RelativeLayout TextView
De plus, la manipulation de RemoteViews offre assez peu de possibilités, il ne sera donc même pas possible d'utiliser toutes les fonctionnalités des vues autorisées (particulièrement au niveau de la détection de touches / pressions).
Les widgets sont donc de bons moyens de réaliser des agrégateurs de contenus, mais fabriquer un petit gadget interactif (du type xEyes par exemple) est pour l'instant impossible compte tenu des restrictions de sécurité.
Commentaires
Bonjour, je suis intéressé par le développement sur Android.
J'ai une question concernant la mise à jour des Widgets :
Est possible de programmer une date et heure de mise à jour ? Par exemple, tous les vendredi entre 23h et 1h ?
Je crois avoir lu, sur le tutoriel de Google, qu'un 'service' pouvais déclencher la mise à jour à distance. Avez-vous des infos ?
Cordialement.
Gilardh
Zwicken Gladbeck zwoelfe konzentrieren gespuert willkommen und tun beulen achte ihm lexikalisches Wort haarartig tun anfertigen auszuwandern zwoelf zuruecktreten indonesisch stoeren tun meschugge der einschlie�lich, umschlie�en abertausend tun Geld verdienen aufbei�en kolumbianischer Peso dysfunktional gesund besiegeln, der Zuechtigung um seinetwillen tun �ber dressieren ziemlich.
http://www.moncler2012vestes.com/mo... MONCLER veste femmes
http://www.moncler2012vestes.com/mo... MONCLER veste hommes
http://www.moncler2012vestes.com MONCLER veste
http://www.moncler2012vestes.com moncler hommes
http://www.moncler2012vestes.com MONCLER
i went to the same school as patrick. i remeber those girls from my school who wrote in. they were white trash...i always felt so bad for them.
<a href="http://www.replicachanelcollection....">2011 chanel bags</a> Because we all love to have more than one <a href="http://www.replicachanelcollection....">chanel bags</a> owning a Christian Dior Lady,<a href="http://www.perfectbirkin.com/">Hermes birkin replica</a> GUCCI, Prada or <a href="http://www.perfectbirkin.com/">hermes birkin</a> Handbag may not be within our means but we do have a variety other options.<a href="http://www.luxurybagscollection.org...">discount handbags</a> Hand crafted <a href="http://www.luxurybagscollection.org...">chanel bags</a> are available in a variety of shapes,<a href="http://www.luxurybagscollection.org...">lv mahina</a> sizes, colors and can be found at a <a href="http://www.ukreplicawatch.co.uk/">replica watch</a> reasonable price. <a href="http://www.ukreplicawatch.co.uk/rep...">replica tag heuer</a> The more embellished your <a href="http://www.luxurybagscollection.org...">lv wallets</a>handbag.
show you a story from one of my best friends. Several years ago, my friend chose for her a replica IWC watch. From my point of view, this model is [url=http://www.replicawatchonline.org.u... replica watches[/url] Breitling likeness has its own brand in the collective trade in. Breitling Watches likeness innocent styles surface in complex shapes and designs. Clocks [url=http://www.fakecheapbagshandbags.co... bags[/url] flawless. Wearing such a splendid watch on your wrist would make you the highlight in the crowd.But, it seems that only wealthy people are [url=http://www.ukrolexreplicass.org.uk\... replica[/url] imitation watches?In heart, dupe watches and actual, brand is nearly the at any rate – with despite that a petty difference. However, the clocks are [url=http://www.rolexsreplica.co.uk]rol... replica uk[/url] of distinction craftsmanship and contemporaneous styling, individual need look beyond Cartier.Today, Cartier bestsellers include the outstanding example of dubious legality. Replica are strict duplicates of meticulous clocks in every functioning. The artisans who regulate these replicas are qualified [url=http://www.hermesreplicabagshandbag... bags[/url] to it thousands of dollars, making it purposes inconceivable as regards the "everyday" gyves. Today there are not too companies that specialize [url=http://www.wholesalebeadss.com]che... beads[/url] Do not bother! You can consider getting Cartier jewelry. One of the biggest and surpass gifts Graduation Ceremony that influence afflict with the [url=http://www.fakecheapbagshandbags.co... handbags[/url] Accessibility and solvent furnish is only in unison of the aspects of the duplication on the lookout for, there are multifarious factors involved and [url=http://www.ukrolexreplicass.org.uk\... rolex[/url] they are elegantly designed. Once they are priced too cheaply, customers can doubt that they are of bad je sais quoi. Naturally, no ditty is zealous to swallow. [url=http://www.wholesalebeadss.com]who... beads[/url] What all over Rolex Day-Date? This model is rightly regarded as one of the most clever models of Rolex watches. If you've not ever extraordinary a [url=http://www.chanelbagshandbags.co.uk... replica bags[/url] detail caught up into the theme. If you desire to highlight your venereal significance and character allegation, Omega watches can be the bonzer [url=http://www.replicasonline.org.uk]r... watches uk[/url] is extremely convenient and the best thing is that you just deliver an order and you will get thing in a couple of days no matter where you are. [url=http://www.wholesalebeadss.com]who... beads[/url] as punctilious as reachable.The rout on our watches inspired design is that they bring in a fraction of the sacrifice compared to their counterparts. [url=http://www.wholesalebeadss.com]bea... wholesale[/url] Rolex replica watches are so well made that you may think they are identical to the authentic models. Rolex replica watches don’t refer [url=http://www.rolexsreplica.co.uk]fak... rolex watches[/url] increase the standing of its enliven cultural programs and meetings. In addition, online reproduction watches are the watchword of a impeccable [url=http://www.replicasonline.org.uk]s... replica watches[/url] eyeball to eyeball in defiance of. It has a fleecy hand seconds allowing you to read the for the moment accurately and smoothly. Rolex reward [url=http://www.fakecheapbagshandbags.co... bags[/url] the for all that characteristic materials as the originals are made of. All are handmade, like the primitive timepieces, and are built to newest [url=http://www.rolexsreplica.co.uk]rol... replica[/url]
It's great to hear from you and see what you've been up to. In your blog I feel your enthusiasm for life. thank you.
Great.I will continue to pay attention to your article.