Outils pour utilisateurs

Outils du site


numero61:python_p._7-9

This time, we’ll set up the Android SDK on our Linux desktop. We’ll also create a virtual Android device, install SL4A and python on it, and do a quick test. Please be aware, this is not something you would want to do for machines that have less than 1 GB of ram. The emulator eats up a huge amount of memory. I’ve tried it on a laptop running Ubuntu with only 512 MB of ram. It WILL work, but it is REALLY slow. Here’s a quick list of what we’ll do. We’ll go step-by-step in a minute. • Install the Java JDK6. • Install the Android SDK starter pack. • Create and setup AVDs. • Test AVD, and install SL4A and Python. In reality, we should also install Eclipse and the Android ADT plugin for Eclipse, but, since we won’t be dealing with Eclipse in this set of articles, we can bypass that. If you want to include those steps, head over to http://developer.android.com/sdk/installing.html to see all the steps in the suggested order. Let’s get started.

Ce mois-ci, nous allons mettre en place le SDK Android sur notre bureau Linux. Nous allons aussi créer un périphérique Android virtuel, installer SL4A et Python dessus, et faire un test rapide.

S'il vous plaît faites attention, ce n'est pas quelque chose qu'il faut faire sur une machine qui a moins de 1 Go de RAM. L'émulateur consomme une énorme quantité de mémoire. Je l'ai essayé sur un ordinateur portable fonctionnant sous Ubuntu avec seulement 512 Mo de RAM. Il fonctionne, mais il est VRAIMENT lent.

Voici une liste rapide de ce que nous allons faire. Nous allons y aller étape par étape dans une minute : • Installer le JDK6 Java. • Installer le pack de démarrage SDK Android. • Créer et configurer les AVD. • Tester AVD et installer SL4A et Python.

En réalité, nous devrions également installer Eclipse et le plugin Android ADT pour Eclipse, mais, puisque nous n'utiliserons pas Eclipse dans cette série d'articles, nous pouvons éviter cela. Si vous souhaitez les inclure, allez voir sur http://developer.android.com/sdk/installing.html pour voir toutes les étapes dans l'ordre suggéré. Nous allons maintenant commencer.

STEP 1 - Java JDK 6 From everything I’ve read and tried, it must be the actual Sun release. OpenJDK is not supposed to work. You can find information on this on the web, but here’s the steps that I did. In a terminal, type the following… sudo add-apt-repository ppa:ferramroberto/java sudo apt-get update sudo apt-get install sun-java6-jdk Once everything here is done, you will want to edit your .bashrc file to set “JAVA_HOME” so everything runs correctly. I used gedit and, at the bottom of the file, I added the following line… export JAVA_HOME=”/usr/lib/jvm/java-6-sun-1.6.0.06” Save the file and move on to step 2.

ÉTAPE 1 - Java JDK 6

D'après tout ce que j'ai lu et essayé, il faut vraiment utiliser la version de Sun. OpenJDK n'est pas censé fonctionner. Vous pouvez trouver des informations à ce sujet sur le web, mais voici les étapes que j'ai suivies. Dans un terminal, tapez les commandes suivantes :

sudo add-apt-repository ppa:ferramroberto/java

sudo apt-get update

sudo apt-get install sun-java6-jdk

Une fois que tout ceci est fait, vous devrez modifier votre fichier .bashrc pour régler « JAVA_HOME » pour que tout fonctionne correctement. J'ai utilisé gedit pour ajouter la ligne suivante à la fin du fichier :

export JAVA_HOME=”/usr/lib/jvm/java-6-sun-1.6.0.06”

Enregistrez le fichier et passez à l'étape 2.

STEP 2 - Android SDK Starter Pack Now the actual “fun” begins. You’ll want to go to developer.android.com/sdk/index.html. This is where the SDK is located. Download the latest version for Linux, which, at the time of this writing, is android-sdk_r18-linux.tgz. Using Archive Manager, unpack it somewhere convenient. I put it in my home directory. Everything runs directly from this folder, so you really don’t have to install anything. So the path for me is /home/greg/android-sdk-linux. Navigate to this folder, then go to the tools folder. There you will find a file called “android”. This is what runs the actual SDK. I created a launcher on my desktop to make it easy to get to. Now the boring part. Run the android file, and the Android SDK Manager will start. It will go out and update the platforms that are available. I will warn you now that this process will take some time, so don’t bother if you don’t have a lot of time to deal with it. For the sake of brevity, I would suggest you get only one platform to start. A good one to begin with is the Android 2.1 platform, since, for the most part, if you develop for an older platform, there should be no problem running on a newer platform. You also need to get the Tools set as well. Simply check the box next to those two items, then click on the install button. Once you get the platform of your choice, and the tool set, you are almost ready to create your first virtual machine.

ÉTAPE 2 - Pack de démarrage Android SDK

Maintenant, la partie « marrante » commence. Rendez-vous sur developer.android.com/sdk/index.html. C'est là que se trouve le SDK. Téléchargez la dernière version pour Linux qui, au moment d'écrire ces lignes, est android-sdk_r18-linux.tgz. À l'aide du Gestionnaire d'archives, décompressez-la dans un dossier approprié. Je l'ai mise dans mon répertoire personnel. Tout fonctionne directement à partir de ce dossier, vous n'avez donc vraiment pas besoin d'installer quoi que ce soit. Ainsi, le chemin pour moi est /home/greg/android-sdk-linux. Allez dans ce dossier, puis allez dans le dossier des outils (« tools »). Vous y trouverez un fichier nommé « android ». C'est lui qui lance réellement le SDK. J'ai créé un lanceur sur mon bureau pour en faciliter l'accès.

Maintenant, la partie ennuyeuse. Exécutez le fichier android ; le gestionnaire de SDK Android va démarrer. Il va mettre à jour les plateformes qui sont disponibles. Je vous préviens maintenant que ce processus prendra un certain temps, alors ne vous embêtez pas si vous n'avez pas beaucoup de temps pour y faire face. Par souci de concision, je vous conseille de n'avoir qu'une plateforme pour commencer. Je vous suggère de commencer par Android 2.1, puisqu'en général si vous développez pour une ancienne plateforme, il ne devrait y avoir aucun problème d'exécution sur une nouvelle plateforme. Vous devez également récupérer l'ensemble des outils. Il suffit de cocher la case à côté de ces deux éléments, puis de cliquer sur le bouton d'installation. Une fois que vous avez obtenu la plateforme de votre choix et l'ensemble d'outils, vous êtes presque prêt à créer votre première machine virtuelle.

STEP 3 - Create and set up your first AVD Back in the Android SDK Manager, select Tools from the main menu, then select Manage AVDs. This will open a new window. Since this is the first time, there won’t be any virtual devices set up. Click on the “New” button. This opens yet another window where we define the properties of the virtual Android device. Here’s the steps that you should use to set up a simple Android emulator device: • Set the name of the device. This is important if you have more than one device. • Set the target platform level. • Set the size of the SD card (see below). • Set the skin resolution. • Create the device. So, In the name text box, type “Test1”. Under the target combo-box, select Android 2.1 - API Level 7. In the text box for “SD Card:” enter 512 and make sure the dropdown shows “MiB”. Under “Skin”, set the resolution to 800×600. (You can play with the other built-in sizes on your own.) Finally, click the “Create AVD” button. Soon, you’ll see a message box saying that the AVD was created.

ÉTAPE 3 - Créer et configurer votre première AVD

Retournez dans le Gestionnaire de SDK Android, sélectionnez Outils (« Tools ») dans le menu principal, puis sélectionnez « Gérer les AVD ». Cela va ouvrir une nouvelle fenêtre. Puisque c'est la première fois, il n'y aura pas encore de périphérique virtuel configuré. Cliquez sur le bouton « Nouveau ». Cela ouvre une autre fenêtre où nous définissons les propriétés du périphérique virtuel Android. Voici les étapes que vous devrez suivre pour mettre en place un dispositif émulateur Android simple : • Définissez le nom de l'appareil. Ceci est important si vous avez plus d'un appareil. • Réglez le niveau de plateforme cible. • Définissez la taille de la carte SD (voir ci-dessous). • Réglez la résolution. • Créez le périphérique.

Par exemple, dans la zone de texte Nom, tapez « Test1 ». Pour la cible, sélectionnez Android 2.1 - API de niveau 7. Dans la boîte pour « Carte SD : », entrez 512 et assurez-vous que la liste affiche « Mio ». Dans « Skin », réglez la résolution à 800×600. (Vous pouvez jouer avec les autres paramètres de tailles.) Enfin, cliquez sur le bouton « Créer AVD ». Vous verrez alors un message disant que l'AVD a été créée.

STEP 4 - Testing the AVD and installing SL4A and Python Now, finally, we can have a bit of fun. Highlight the AVD you just created and click on the Start button. In the dialog box that pops up, simply click the “Launch” button. Now, you have to wait a few minutes for the virtual device to be created in memory, and the Android platform to be loaded and started. (We’ll talk about speeding this process up in later runs.) Once the AVD starts up and you have the “home” screen up, you will install SL4A. Using the browser or the google web search box on the home screen, search for “sl4a”. Go to the downloads page, and you’ll eventually find the web page for the downloads at http://code.google.com/p/android-scripting/downloads/list. Scroll down the page until you get to the sl4a_r5 link. Open the link and tap on the “sl4a_r5.apk” link. Notice I said “tap” rather than “click”. Start thinking about using your finger to tap the screen rather than clicking the mouse. It will make your programming transition easier. You’ll see the download start. You may have to pull down the notification bar at the top to get to the downloaded file. Tap on that, then tap the install button.

ÉTAPE 4 - Test de l'AVD et installation de SL4A et Python

Maintenant, enfin, nous pouvons nous amuser un peu. Mettez en surbrillance l'AVD que vous venez de créer et cliquez sur le bouton Démarrer. Dans la boîte de dialogue qui apparaît, cliquez simplement sur le bouton « Lancer ». Vous devez alors attendre quelques minutes pour que le périphérique virtuel soit créé dans la mémoire et que la plateforme Android soit chargée et démarrée. (Nous reparlerons de l'accélération de ce processus dans un prochain article.)

Une fois que l'AVD a démarré et que vous avez l'écran d'accueil, vous allez installer SL4A. En utilisant le navigateur ou la boîte de recherche Google Web sur l'écran d'accueil, recherchez « sl4a ». Allez à la page des téléchargements et vous finirez par trouver la page web pour les téléchargements http://code.google.com/p/android-scripting/downloads/list.

Faites défiler la page jusqu'à ce que vous obteniez le lien sl4a_r5. Ouvrez le lien et tapez sur le lien « sl4a_r5.apk ». Remarquez que j'ai dit « tapez » plutôt que « cliquez ». Commencez à penser à votre doigt qui appuie sur l'écran plutôt que de cliquer avec la souris. Cela facilitera votre transition vers la programmation. Vous verrez le début de téléchargement. Vous pourriez avoir à tirer vers le bas la barre de notification en haut pour obtenir le fichier téléchargé. Tapez sur le fichier, puis sur le bouton d'installation.

Once the file is downloaded, you’ll be presented with the option to open the downloaded app or to tap “Done” to exit the installer. Here we will want to tap “Open”. Now SL4A will start. You’ll probably see a dialog asking if you will agree to usage tracking. Either accept or refuse this - it’s up to you. Before we go any farther, you should know some keyboard shortcuts that will help you move around. Since we don’t have a “real” Android device, buttons like Back, Home, and Menu, aren’t available. You’ll need them to navigate around. Here’s a few important shortcuts. Back - Escape Home - Home Menu - F2

Une fois le fichier téléchargé, vous verrez la possibilité d'ouvrir l'application téléchargée ou de taper sur « Terminé » pour quitter le programme d'installation. Ici, il faut taper sur « Ouvrir ».

Maintenant SL4A va démarrer. Vous verrez probablement une boîte de dialogue vous demandant si vous acceptez un suivi de l'utilisation. C'est à vous de décider si vous voulez accepter ou refuser. Avant d'aller plus loin, vous devriez connaître quelques raccourcis clavier qui vous aideront à vous déplacer. Comme nous n'avons pas un « vrai » appareil Android, les boutons Retour, Accueil et Menu ne sont pas disponibles. Vous en aurez besoin pour naviguer. Voici quelques raccourcis importants :

Retour - Échap Accueil - Début Menu - F2

Now we will want to download and install python into SL4A. To do this, first tap Menu (press F2). Select “View” from the menu. Now select “Interpreters”. It looks like nothing happened, but tap Menu again (F2), then select “Add” from the popup. Now scroll down and select “Python 2.6.2”. This will download the base package for Python for Android. Install the package, then open it. You will be presented with four options. Install, Import Modules, Browse Modules, and Uninstall Module. Tap on Install. This will start downloading and installing all the pieces of the latest Python for Android. This can take a few minutes. Once everything is done, tap Back (escape key) until you get to the SL4A Interpreters screen. Now everything is loaded for us to play in Python on Android. Tap Python 2.6.2, and you’ll be in the “standard” Python shell. This is just like the shell on your desktop. Type the following three lines, one at a time, into the shell. Be sure to wait for the “»>” prompt each time.

Maintenant, nous voulons télécharger et installer Python dans SL4A. Pour faire cela, appuyez d'abord sur Menu (F2). Sélectionnez « Affichage » dans le menu. Maintenant, sélectionnez « Interprètes ». On dirait que rien ne se passe, mais appuyez sur Menu à nouveau (F2), puis sélectionnez « Ajouter » dans le menu contextuel. Maintenant, faites défiler vers le bas et sélectionnez « Python 2.6.2 ». Ceci va télécharger le paquet de base Python pour Android. Installez le paquet puis ouvrez-le. Vous verrez quatre options. Installer, importer des modules, parcourir les modules et désinstaller un module. Tapez sur Installer. Cela va démarrer le téléchargement et l'installation de tous les morceaux de la dernière version de Python pour Android. Cela peut prendre quelques minutes.

Une fois que tout est terminé, appuyez sur Retour (touche Échap) jusqu'à ce que vous arriviez à l'écran des interprètes SL4A. Maintenant tout est chargé pour que nous puissions jouer en Python sur Android. Tapez sur Python 2.6.2 et vous vous trouverez dans la ligne de commande standard de Python. C'est exactement comme la ligne de commande sur votre bureau. Saisissez les trois lignes suivantes, une à la fois, dans la ligne de commande. Assurez-vous d'attendre l'invite « »> » à chaque fois.

import android droid = android.Android() droid.makeToast(“Hello from Python on Android”) After you type the last line and press Enter, you’ll see a rounded corner box at the center bottom of the shell that says “Hello from Python on Android”. That’s what the “droid.makeToast” command does. You’ve written your first Python script for Android. Neat, huh?

import android
droid = android.Android()
droid.makeToast("Bonjour depuis Python pour Android")

Après avoir tapé la dernière ligne et appuyé sur Entrée, vous verrez une fenêtre aux coins arrondis centrée en bas de la ligne de commande, qui dit : « Bonjour depuis Python pour Android ». C'est ce que fait la commande droid.makeToast.

Vous avez écrit votre premier script Python pour Android. Chouette, hein ?

Now let’s create a shortcut on the Android home screen. Tap the Home key (Home button). If you chose the 2.1 platform, you should see a slider bar on the far right of the screen. If you chose another platform, it might be a square or rectangle consisting of small squares. Either way, this gets you to the Apps screen. Tap that, and find the SL4A icon. Now perform a “long tap” (long click), which will create a shortcut on the Home screen. Move the shortcut wherever you want it. Next, we will create our first saved script. Go back into SL4A. You should be presented with the sample scripts that come with Python 4 Android. Tap the Menu button and select “Add”. Select “Python 2.6.2” from the list. You’ll be presented with the script editor. At the top is the filename box with “.py” already filled out. Below that is the editor window that already has the first two lines of our program entered for us. (I included them below in italics so you can check it. We also used these two lines in our first sample.)

Maintenant, nous allons créer un raccourci sur l'écran d'accueil d'Android. Tapez sur la touche Accueil (bouton Début). Si vous avez choisi la plateforme 2.1, vous devriez voir une barre de défilement à l'extrême droite de l'écran. Si vous avez choisi une autre plateforme, il se pourrait que ce soit un carré ou un rectangle composé de petits carrés. De toutes les façons, cela vous amène à l'écran des Applis. Tapez dessus et trouvez l'icône SL4A. Maintenant effectuez un « taper long » (clic long), qui créera un raccourci sur l'écran d'accueil. Déplacez le raccourci où vous le souhaitez.

Ensuite nous allons créer notre premier script sauvegardé. Retournez dans SL4A. Vous devriez voir les exemples de scripts fournis avec Python pour Android. Tapez sur le bouton Menu et sélectionnez « Ajouter ». Sélectionnez « Python 2.6.2 » dans la liste. Vous verrez l'éditeur de script. Au sommet se trouve la boîte de nom de fichier avec « .py » déjà rempli. En dessous se trouve la fenêtre de l'éditeur qui contient déjà les deux premières lignes de notre programme saisies pour nous. (Je les ai inclues ci-dessous en italique pour que vous puissiez le vérifier. Nous avons également utilisé ces deux lignes dans notre premier exemple.)

import android droid = android.Android() Now, enter the following two lines to the python script. uname = droid.dialogGetInput(“What’s your name?”) droid.makeToast(“Hello %s from Python on Android”) % uname.result

import android
droid = android.Android()

Maintenant saisissez les deux lignes suivantes dans le script python :

uname = droid.dialogGetInput("Quel est votre nom ?")
droid.makeToast("Bonjour %s depuis Python pour Android") % uname.result

The first new line will create a dialog box (droid.dialogGetInput()) that asks for the user’s name. The response is returned to our program in uname.result. We’ve already used the droid.makeToast() function. Name the file andtest1.py, then tap Done, and tap “Save & Run”. If everything worked, you should see a dialog box asking for your name. After you enter it, you should see the alert at the bottom of the screen saying “Hello Your Name from Python on Android”. That’s all for this time. For now, there’s a TON of documentation about SL4A for free on the web. You can play a bit on your own until next time. I’d suggest that you start by going to http://code.google.com/p/android-scripting/wiki/Tutorials.

La première ligne nouvelle crée une boîte de dialogue (droid.dialogGetInput()) qui demande son nom à l'utilisateur. La réponse est retournée à notre programme dans uname.result. Nous avons déjà utilisé la fonction droid.makeToast().

Nommez le fichier andtest1.py, puis tapez sur Terminé puis sur « Enregistrer et Exécuter ». Si tout s'est bien passé, vous devriez voir une boîte de dialogue vous demandant votre nom. Après l'avoir saisi, vous devriez voir l'alerte en bas de l'écran qui affiche : « Bonjour Votre nom depuis Python pour Android ».

C'est tout pour cette fois-ci. Pour l'instant, il y a une tonne de documentation gratuite sur SL4A sur ​​le web. Vous pouvez jouer un peu tout seul jusqu'à la prochaine fois. Je vous suggère de commencer par http://code.google.com/p/android-scripting/wiki/Tutorials.

ANNONCE Santa Clara Convention Center O'Reilly are looking forward to celebrating Velocity's 5th Year with you June 25-27, at the Santa Clara Convention Center. You'll meet the smartest people working in web performance and operations at the O'Reilly Velocity Conference. Web and mobile users expect better performance than ever before. To meet, and exceed, their expectations, you need to master a daunting array of web performance, operations, and mobile performance issues. Velocity offers the best opportunity to learn the newest info on what you need to know to build a faster and stronger web. Take advantage of this rare opportunity to meet face-to-face with a cadre of industry leaders who are taking web performance and operations to the next level. Velocity packs a wealth of big ideas, know-how, and connections into three concentrated days. You'll be able to apply what you've learned immediately and you'll be well prepared for what lies ahead with four in-depth tracks covering the key aspects of web performance, operations, mobile performance, and Velocity culture. Velocity has sold out the last two years, so if you want to reserve your spot at Velocity 2012, register now and save an additional 20% with code FULLCIR.

ANNONCE

Centre de conventions de Santa Clara

O'Reilly est impatient de célébrer la 5ème année de Velocity avec vous du 25 au 27 juin au Santa Clara Convention Center. Vous rencontrerez les gens les plus intelligents qui travaillent sur les performances Web et les opérations lors de la conférence O'Reilly Velocity. Les utilisateurs du Web et du mobile s'attendent à des performances meilleures que jamais. Pour répondre à leurs attentes voire les dépasser, vous avez besoin de maîtriser les performances Web, les opérations et les problèmes de performances mobiles. Velocity vous offre la meilleure occasion d'apprendre les dernières infos sur ce que vous devez savoir pour construire un Web plus rapide et plus fort.

Profitez de cette occasion rare de rencontrer en face-à-face un groupe de leaders de l'industrie qui emmènent les performances Web et les opérations à un niveau supérieur. Velocity apporte une foule de grandes idées, le savoir-faire et les connexions en trois jours extrêmement remplis. Vous pourrez appliquer immédiatement ce que vous avez appris et vous serez bien préparé pour ce qui nous attend, avec quatre ateliers en profondeur portant sur les aspects clés de la performance Web, des opérations, de la performance mobile et de la culture Velocity.

Les deux dernières années, Vélocity a fait salle comble ; ainsi, si vous souhaitez réserver votre place pour Velocity 2012, inscrivez-vous maintenant et économisez 20% supplémentaires avec le code FULLCIR.

numero61/python_p._7-9.txt · Dernière modification : 2012/07/20 12:34 de andre_domenech