SlideShare une entreprise Scribd logo
1  sur  60
Télécharger pour lire hors ligne
Android Development
                            using Python


                               +
                               George Goh
                               10 June 2011
                               PyCon APAC
                                    1
Friday, June 10, 2011
HP Labs Singapore


                        http://www.hpl.hp.com/singapore/




                                       2
Friday, June 10, 2011
Agenda

                        • Android Programming (Java vs. Python)
                        • Python Examples / UI Examples
                        • A More Complex Example

                                            3
Friday, June 10, 2011
Android Rocks!!!




                               4
Friday, June 10, 2011
Why Python?




                             5
Friday, June 10, 2011
Programming Android




                                 6
Friday, June 10, 2011
Plus Python




                             7        http://www.blangy.com/Photos.html
Friday, June 10, 2011
A simple program




                               8
Friday, June 10, 2011
Simple Program in Java
                 package com.spodon.pycon;

                 import     android.app.Activity;
                 import     android.app.AlertDialog;
                 import     android.content.DialogInterface;
                 import     android.os.Bundle;
                 import     android.widget.EditText;
                 import     android.widget.Toast;

                 public class Demo extends Activity {
                 	
                     private EditText mEditText = null;
                 	
                     @Override
                     public void onCreate(Bundle savedInstanceState) {
                         super.onCreate(savedInstanceState);
                         setContentView(R.layout.main);

                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
                            builder.setTitle("Hello!");
                            builder.setMessage("What is your name?");
                            mEditText = new EditText(this);
                            builder.setView(mEditText);

                             builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                 	      	     	   @Override
                 	      	     	   public void onClick(DialogInterface dialog, int which) {
                 	      	     	   	   Toast.makeText(Demo.this, "Cancelled", Toast.LENGTH_SHORT).show();
                 	      	     	   }
                 	      	     });

                 ...
                                                                    9
Friday, June 10, 2011
Simple Program in Python
                        import android

                        droid = android.Android()
                        name = droid.getInput("Hello!", "What is your name?")
                        droid.makeToast("Hello, %s" % name.result)




                 • Java program: 35 SLOC
                 • Equivalent Python program: 4 SLOC
                                                 10
Friday, June 10, 2011
Android module
                        import android

                        droid = android.Android()
                        name = droid.getInput("Hello!", "What is your name?")
                        droid.makeToast("Hello, %s" % name.result)



                        • Exposes android functionality via an
                           Android() object.
                        • Talks to a service called SL4A (Scripting
                           Layer for Android).

                                                 11
Friday, June 10, 2011
Invoking functionality
                        import android

                        droid = android.Android()
                        name = droid.getInput("Hello!", "What is your name?")
                        droid.makeToast("Hello, %s" % name.result)


                           Python Interpreter                               Android




                                                    functionality exposed
                                                      via RPC methods

                                       android.py
                                                                                  SL4A


                                                             12
Friday, June 10, 2011
Scripting Layer for
                         Android (SL4A)


                        Search keyword: android-scripting
                                       13
Friday, June 10, 2011
Scripting Layer for
                  Android (SL4A)

                        • Started in 2009 by Damon Kohler
                        • 20% time project at Google.
                        • Supports Python, Ruby, Perl, Lua, JavaScript,
                          BeanShell and more.



                                              14
Friday, June 10, 2011
Users of SL4A


                        • Rockets
                         •   SmallSat




                                        15   http://www.flickr.com/photos/jurvetson/
Friday, June 10, 2011
Users of SL4A
                        Cellbots - http://www.cellbots.com




                                            16          http://www.flickr.com/photos/motorbikematt/
Friday, June 10, 2011
SL4A Functionality
                        •   ActivityResult            •   MediaRecorder
                        •   Android                   •   Phone
                        •   ApplicationManager        •   Preferences
                        •   BatteryManager            •   SensorManager
                        •   Camera                    •   Settings
                        •   CommonIntents             •   Sms
                        •   Contacts                  •   SpeechRecognition
                        •   Event                     •   ToneGenerator
                        •   EyesFree                  •   WakeLock
                        •   Location                  •   Wifi
                        •   MediaPlayer               •   UI


                                                 17
Friday, June 10, 2011
Examples
                          Speech Recognition
               import android

               droid = android.Android()
               message = droid.recognizeSpeech("What is your command?")
               droid.makeToast("You said: %s" % message.result)




                                           18
Friday, June 10, 2011
Examples
                                Text-to-Speech
               import android

               droid = android.Android()
               droid.vibrate()
               droid.ttsSpeak("Hello, this is android speaking!")




                                           19
Friday, June 10, 2011
Examples
                                  Web View

               import android

               droid = android.Android()
               message = droid.webViewShow("http://xkcd.com/353/")




                                           20
Friday, June 10, 2011
Examples
                                        SMS

               import android

               droid = android.Android()
               droid.smsSend(someNumber,"Let’s meet for drinks!")




                                           21
Friday, June 10, 2011
Dealing with UI



                               22
Friday, June 10, 2011
UI

                        • WebView Frontend (HTML + Javascript)
                        • Python Backend
                        • Frontend talks to Backend using Events

                                            23
Friday, June 10, 2011
Events

                        • eventPost(name, data)
                        • eventWaitFor(eventName, timeout)
                        • eventClearBuffer()
                        • eventPoll(number_of_events)
                        • eventWait()
                                           24
Friday, June 10, 2011
example.py
                                  Example
               import android

               droid = android.Android()
               droid.webViewShow("/sdcard/sl4a/scripts/html/example.html")

               result = droid.eventWaitFor("EVENT_A").result[“data”]
               self.droid.log("Received data from EVENT_A: " + result)

               example.html
               ...
               <script language= "javascript" type= "text/javascript">
                 var droid = new Android();
                 var date = new Date();

                 droid.eventPost("EVENT_A", "Page Loaded On " + date);
               </script>
               ...
                                           25
Friday, June 10, 2011
Before we move on...
                        • What was discussed so far
                         •   Using the android.py module in Python
                             programs.

                         •   android.py talks to SL4A, which exposes Android
                             functionality to clients.

                         •   UI can be built using HTML+Javascript, and it
                             can talk to Python backend using SL4A events.


                                                26
Friday, June 10, 2011
A more complete
                           example?


                               27
Friday, June 10, 2011
Control robots!




                               28   http://www.flickr.com/photos/motorbikematt/
Friday, June 10, 2011
The Design
                                        direction
                                         control                     Arduino
                                                         Bluetooth
                        FWD
                                                          module     Cellbots
            LEFT        STOP   RIGHT                                 firmware
                        BACK

                                                                          analog
                                                                          motor
                                                                          control




                                                    29
Friday, June 10, 2011
The Design
                                                        Arduino
  Bluetooth
   module
              Arduino
              Cellbots
                                  •   Cellbots project for firmware
              firmware             •   PDE files on Cellbots site

                                                        Android
                                  •
                   FWD


           LEFT    STOP   RIGHT       HTML + Javascript for frontend UI

                                  •
                   BACK


                                      Python for backend, Cellbot control

                                  •   Bluetooth module required (Py4A project)

                                                   30
Friday, June 10, 2011
Cellbot Controller

                        • Looks for Cellbot devices via Bluetooth.
                        • Connects to a selected device and controls
                          its movement.
                        • Invokes WebView to display UI.
                        • Interacts with UI using SL4A events.
    Code available at https://github.com/georgegoh/cellbot-controller
                                             31
Friday, June 10, 2011
Connecting to the Device
                    cellbot.py
                                                 1. Display scan view
                                  Start                                        scan.html
                                                2. even t(scanBluetooth)       User clicks “Scan”
                        Scan for list of
                        nearby devices     3. event(bluetoothDevicesFound)
                              and post
                                                                               UI shows devices list

                                                             luetoothDevice)
            Connect to selected            4. event(connectB                   User selects device
                         device




                                                          32
Friday, June 10, 2011
Bluetooth scanning
   def scan_bluetooth(self, arg):
       """ Discover nearby Bluetooth devices and trigger an SL4A
           event "bluetoothDevicesFound" with the list of devices
           found.
       """
       self.droid.log("Scanning bluetooth devices")
       self.discovered_devices = 
               bluetooth.discover_devices(lookup_names=True)
       self.droid.log("Devices found: " + 
                      str(self.discovered_devices))
       self.droid.eventPost("bluetoothDevicesFound",
                            json.dumps(self.discovered_devices))


    Code available at https://github.com/georgegoh/cellbot-controller
                                    33
Friday, June 10, 2011
Bluetooth connection

   def connect_bluetooth_device(self, bd_addr):
       """ Connect to a Bluetooth device specified by the bd_addr
           address and display the control view for the device.
       """
       service = bluetooth.find_service(uuid=CELLBOT_UUID,
                                        address=bd_addr)[0]
       self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
       self.socket.connect((service["host"], service["port"]))
       self.droid.webViewShow(CONTROL_VIEW)




    Code available at https://github.com/georgegoh/cellbot-controller
                                    34
Friday, June 10, 2011
Controlling the Device
                    cellbot.py
                                         1. Display control view
                                 Start                             control.html
                                             2. event(move)        User clicks a
                                                                   direction
                        Send direction
                         to connected
                               cellbot




                                                   35
Friday, June 10, 2011
Motion Control
  def move(self, direction):
      """ Move a connected Cellbot in one of the following directions:
              f - Forward
              b - Back
              l - Left
              r - Right
              s - Stop
      """
      if self.socket:
          self.socket.send(direction + "n")



    Code available at https://github.com/georgegoh/cellbot-controller
                                    36
Friday, June 10, 2011
Frontend HTML/JS Control 1
  <head>
    <title>Robot demo</title>
    <script type="text/javascript" src="./js/mootools.js"></script>
    <script language="javascript" type="text/javascript">
      var droid=new Android();

      function postToPython(data) {
        droid.eventPost("PYTHON", JSON.stringify(data));
      }

      function move(direction) {
        postToPython({action: "move", data: direction});
      }

      window.addEvent("domready", function() {
        $('bFwd').addEvent('click', function() { move("f"); });
        $('bLeft').addEvent('click', function() { move("l"); });
        $('bStop').addEvent('click', function() { move("s"); });
        $('bRight').addEvent('click', function() { move("r"); });
        $('bBack').addEvent('click', function() { move("b"); });
        $('bExit').addEvent('click', function() { postToPython
  ({action:"EXIT", data:""}); });
      });
    </script>
  </head>                             37
Friday, June 10, 2011
Frontend HTML/JS Control 2

  <body>
    <table align=center>
      <tr>
        <td />
        <td align=center><button id="bFwd">FWD</button></td>
        <td />
      </tr>
      <tr>
        <td align=center><button id="bLeft">LEFT</button></td>
        <td align=center><button id="bStop">STOP</button></td>
        <td align=center><button id="bRight">RIGHT</button></td>
      </tr>
      <tr>
        <td />
        <td align=center><button id="bBack">BACK</button></td>
        <td />
      </tr>
    </table>
    <button id="bExit">EXIT</button>
  </body>
                                    38
Friday, June 10, 2011
Python for
                         Android (Py4A)

                        • Additional python modules added:
                          - Bluez, Twisted, Zope, pyEphem
                        • Current maintainers:
                          - Naranjo Manuel Francisco
                          - Robbie Matthews


                                             39
Friday, June 10, 2011
References
                        •   Scripting Layer for Android
                            http://code.google.com/p/android-scripting

                        •   Python for Android
                            http://code.google.com/p/python-for-android

                        •   In Love with a Droid
                            http://android-scripting.blogspot.com/

                        •   Cellbots
                            http://www.cellbots.com



                                                       40
Friday, June 10, 2011
Acknowledgements

                        • Damon Kohler
                        • Robbie Matthews
                        • Colleagues @ HP Labs Singapore

                                           41
Friday, June 10, 2011
?

                        42
Friday, June 10, 2011
Thank you
                                   @georgegoh
                           https://github.com/georgegoh/
                        http://www.linkedin.com/in/georgegoh

                                         43
Friday, June 10, 2011
fin



                        44
Friday, June 10, 2011
Bonus/Misc Slides



                                45
Friday, June 10, 2011
Event loop
  while action != "EXIT":
      self.droid.log("Python: Waiting for event.")
      event_data = self.droid.eventWaitFor("PYTHON").result["data"]
      self.droid.log("Python: Event received. Processing...")

            # unpack the event data and perform action(if available).
            properties = json.loads(event_data)
            self.droid.log("Result: " + str(properties))
            action = properties["action"]
            if action in self.handlers:
                self.handlers[action](properties["data"])



    Code available at https://github.com/georgegoh/cellbot-controller
                                         46
Friday, June 10, 2011
Packaging your app
           •       Download the template project archive
                 •      http://android-scripting.googlecode.com/hg/android/
                        script_for_android_template.zip

           •       Modify the following according to your project
                 •      Import into Eclipse

                 •      Refactor package name from com.dummy.fooforandroid to
                        your package name.

                 •      Modify or put your script into the res/raw directory.

                 •      http://code.google.com/p/android-scripting/wiki/SharingScripts

                                                   47
Friday, June 10, 2011
How SL4A works

                        • Android functionality is abstracted into
                          methods.
                        • These methods are grouped in subsystems
                          called ‘Facades’.
                        • A JSON-RPC server exposes the methods
                          contained in these Facades.


                                              48
Friday, June 10, 2011
SL4A Architecture

                                                                              Facade 0


                                                                                 .
                        Client   functionality exposed
                                   via RPC methods
                                                              FacadeManager      .
                                                                                 .
                                                              JsonRpcServer
                                                                              Facade N




                                                         49
Friday, June 10, 2011
Facades
                        • A facade represents a
                            collection of functionality    RPCReceiver


                        •   @Rpc annotation                        <<implements>>

                            exposes methods                XYZFacade

                        •   @RpcParameter,                <<Rpc>> + doIt()


                            @RpcDefault,
                            @RpcOptional describe
                            method arguments.

                                                50
Friday, June 10, 2011
Facades
  public void dialogCreateInput(final String title, final String message, final String text)
      throws InterruptedException {
    dialogDismiss();
    mDialogTask = new AlertDialogTask(title, message);
    ((AlertDialogTask) mDialogTask).setTextInput(text);
  }



  Common/src/com/googlecode/android_scripting/facade/ui/UIFacade.java
  public class UiFacade extends RpcReceiver {
                                                          RpcReceiver   is the abstract
      [...]                                               parent of all Facade classes

    @Rpc(description = "Create a text input dialog.")      @Rpc annotation to indicate
    public void dialogCreateInput(                         method is exposed via RPC
        @RpcParameter(name = "title", description = "title of the input box") @RpcDefault("Value") final String title,
        @RpcParameter(name = "message", description = "message to display above the input box") @RpcDefault("Please
  enter value:") final String message,
        @RpcParameter(name = "defaultText", description = "text to insert into the input box") @RpcOptional final
  String text)
        throws InterruptedException { used in
                         @RpcParameter
      dialogDismiss(); generating user-readable                                         Default values can be
                              descriptions
      mDialogTask = new AlertDialogTask(title, message);                                 specified using the
      ((AlertDialogTask) mDialogTask).setTextInput(text);                              @RpcDefault annotation
    }

      [...]
  }


                                                           51
Friday, June 10, 2011
Code details
                 For details, see:
                 • AndroidProxy
                 • FacadeManagerFactory
                 • FacadeManager
                 • FacadeConfiguration
                                     52
Friday, June 10, 2011
Facades


         http://code.google.com/p/android-scripting/wiki/ApiReference




                                      53
Friday, June 10, 2011
Remote Control


                        •   Write programs using your computer keyboard and
                            monitor and control an Android device remotely.
                        •   Start a SL4A server on your Android, export some
                            environment variables and import the “android.py”
                            module.
                        •   http://bit.ly/startpy4a


                                                      54                        http://xkcd.com/722/
Friday, June 10, 2011
SL4A Architecture

              Language Interpreter                                                Facade 0


                                                                                     .
                                     functionality exposed
                                       via RPC methods
                                                                  FacadeManager      .
                          Language                                                   .
                           specific
                           library                                JsonRpcServer
                                                                                  Facade N




                                                             55
Friday, June 10, 2011
What you need
                        • On your dev machine
                         • Android SDK
                         • Python 2.6
                        • On your Android
                         • Barcode Scanner

                                         56
Friday, June 10, 2011
If you don’t have a
                         barcode scanner
                         1. Start the Android Market App.
                         2. Search for pub: “ZXing Team”
                         3. Install “Barcode Scanner”


                                          57
Friday, June 10, 2011
So I’ve installed
                        SL4A and Py4A.


                         What’s next?




                               58
Friday, June 10, 2011
Install more...
                        • Py4A is not the Python environment.
                        • It is the manager for the Python
                          interpreter, extras, and scripts.
                        • Extras => libraries
                        • Scripts => sample python scripts to get you
                          started.


                                              59
Friday, June 10, 2011
Install the env


                        • Start “Python for
                          Android”

                        • Click “Install”


                                            60
Friday, June 10, 2011

Contenu connexe

Tendances

Python for the C# developer
Python for the C# developerPython for the C# developer
Python for the C# developerMichael Kennedy
 
用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務Bo-Yi Wu
 
game project presentation
game project presentationgame project presentation
game project presentationKavi Kumar
 
A commercial open source project in Python
A commercial open source project in PythonA commercial open source project in Python
A commercial open source project in Pythonjbrendel
 
Python games
Python gamesPython games
Python gamesmolw
 
Pythonistaで始めるiOSプロトタイプ開発
Pythonistaで始めるiOSプロトタイプ開発Pythonistaで始めるiOSプロトタイプ開発
Pythonistaで始めるiOSプロトタイプ開発Yusuke Muraoka
 
Introduction to Python - Code Heroku
Introduction to Python - Code HerokuIntroduction to Python - Code Heroku
Introduction to Python - Code Herokucodeheroku
 
Is python just a fad or here to stay
Is python just a fad or here to stayIs python just a fad or here to stay
Is python just a fad or here to staySarah Walsh
 
GCE 上搭配 Cloud Storage 建置 Drone CI
 GCE 上搭配 Cloud Storage 建置 Drone CI GCE 上搭配 Cloud Storage 建置 Drone CI
GCE 上搭配 Cloud Storage 建置 Drone CIMING JUI Chen
 
Python games (pygames)
Python games (pygames)Python games (pygames)
Python games (pygames)Ahmed Alyazji
 
TypeScript 101 - We RISE Tech Conference
TypeScript 101 - We RISE Tech ConferenceTypeScript 101 - We RISE Tech Conference
TypeScript 101 - We RISE Tech ConferenceFrances Coronel
 
Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...
Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...
Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...Andrzej Jóźwiak
 
Python slide basic to advanced english tutorial
Python slide basic to advanced english tutorialPython slide basic to advanced english tutorial
Python slide basic to advanced english tutorialmasukmia.com
 
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)Evan Lin
 
Best Python IDEs
Best Python IDEsBest Python IDEs
Best Python IDEsBenishchoco
 

Tendances (20)

Python for the C# developer
Python for the C# developerPython for the C# developer
Python for the C# developer
 
用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務
 
game project presentation
game project presentationgame project presentation
game project presentation
 
A commercial open source project in Python
A commercial open source project in PythonA commercial open source project in Python
A commercial open source project in Python
 
Python games
Python gamesPython games
Python games
 
Pythonistaで始めるiOSプロトタイプ開発
Pythonistaで始めるiOSプロトタイプ開発Pythonistaで始めるiOSプロトタイプ開発
Pythonistaで始めるiOSプロトタイプ開発
 
Introduction to Python - Code Heroku
Introduction to Python - Code HerokuIntroduction to Python - Code Heroku
Introduction to Python - Code Heroku
 
Is python just a fad or here to stay
Is python just a fad or here to stayIs python just a fad or here to stay
Is python just a fad or here to stay
 
Django
DjangoDjango
Django
 
GCE 上搭配 Cloud Storage 建置 Drone CI
 GCE 上搭配 Cloud Storage 建置 Drone CI GCE 上搭配 Cloud Storage 建置 Drone CI
GCE 上搭配 Cloud Storage 建置 Drone CI
 
Pyconza(2)
Pyconza(2)Pyconza(2)
Pyconza(2)
 
Python games (pygames)
Python games (pygames)Python games (pygames)
Python games (pygames)
 
TypeScript 101 - We RISE Tech Conference
TypeScript 101 - We RISE Tech ConferenceTypeScript 101 - We RISE Tech Conference
TypeScript 101 - We RISE Tech Conference
 
Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...
Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...
Introduction to the Kotlin programming language - Andrzej Jóźwiak - JUG Łódź ...
 
Python Usefulness
Python UsefulnessPython Usefulness
Python Usefulness
 
Python slide basic to advanced english tutorial
Python slide basic to advanced english tutorialPython slide basic to advanced english tutorial
Python slide basic to advanced english tutorial
 
Python for beginners
Python for beginnersPython for beginners
Python for beginners
 
The Awesomeness of Go
The Awesomeness of GoThe Awesomeness of Go
The Awesomeness of Go
 
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)
 
Best Python IDEs
Best Python IDEsBest Python IDEs
Best Python IDEs
 

En vedette

Python for Android
Python for AndroidPython for Android
Python for Androidphlax
 
Workshop Python para Android
Workshop Python para AndroidWorkshop Python para Android
Workshop Python para AndroidRafael Sanches
 
Desenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em PythonDesenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em PythonRelsi Maron
 
Mémento technique du bâtiment facades
Mémento technique du bâtiment facadesMémento technique du bâtiment facades
Mémento technique du bâtiment facadesKhadime Dramé
 
Python PPT
Python PPTPython PPT
Python PPTEdureka!
 
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?Sang-ho Choi
 
Facade légére 02
Facade légére 02Facade légére 02
Facade légére 02Sami Sahli
 
Facade légére 01
Facade légére 01Facade légére 01
Facade légére 01Sami Sahli
 
Murs de façade
Murs de façadeMurs de façade
Murs de façadeSami Sahli
 

En vedette (9)

Python for Android
Python for AndroidPython for Android
Python for Android
 
Workshop Python para Android
Workshop Python para AndroidWorkshop Python para Android
Workshop Python para Android
 
Desenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em PythonDesenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em Python
 
Mémento technique du bâtiment facades
Mémento technique du bâtiment facadesMémento technique du bâtiment facades
Mémento technique du bâtiment facades
 
Python PPT
Python PPTPython PPT
Python PPT
 
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
 
Facade légére 02
Facade légére 02Facade légére 02
Facade légére 02
 
Facade légére 01
Facade légére 01Facade légére 01
Facade légére 01
 
Murs de façade
Murs de façadeMurs de façade
Murs de façade
 

Similaire à Pycon2011 android programming-using_python

Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbikailan
 
Android Development Slides
Android Development SlidesAndroid Development Slides
Android Development SlidesVictor Miclovich
 
PhoneGap Talk @ Sencha Con 2010
PhoneGap Talk @ Sencha Con 2010PhoneGap Talk @ Sencha Con 2010
PhoneGap Talk @ Sencha Con 2010alunny
 
Android presentation 2011
Android presentation 2011Android presentation 2011
Android presentation 2011Bram Vandeputte
 
Beginning Android Development
Beginning Android DevelopmentBeginning Android Development
Beginning Android DevelopmentJosé Ferreiro
 
Google Developer Group(GDG) DevFest Event 2012 Android talk
Google Developer Group(GDG) DevFest Event 2012 Android talkGoogle Developer Group(GDG) DevFest Event 2012 Android talk
Google Developer Group(GDG) DevFest Event 2012 Android talkImam Raza
 
Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...Matteo Collina
 
2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathonikailan
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011sullis
 
Dojo Mobile
Dojo MobileDojo Mobile
Dojo Mobiledylanks
 
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Goikailan
 
Flowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock
 
Building Cross-Platform Mobile Apps
Building Cross-Platform Mobile AppsBuilding Cross-Platform Mobile Apps
Building Cross-Platform Mobile AppsTroy Miles
 
HTML5: Toolkits and Gaps
HTML5: Toolkits and GapsHTML5: Toolkits and Gaps
HTML5: Toolkits and Gapsdylanks
 
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016Loïc Knuchel
 
Mobile App Testing ScanAgile 2012
Mobile App Testing ScanAgile 2012Mobile App Testing ScanAgile 2012
Mobile App Testing ScanAgile 2012Daniel Knott
 

Similaire à Pycon2011 android programming-using_python (20)

Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodb
 
Android Development Slides
Android Development SlidesAndroid Development Slides
Android Development Slides
 
What is Python?
What is Python?What is Python?
What is Python?
 
Phonegap
PhonegapPhonegap
Phonegap
 
PhoneGap Talk @ Sencha Con 2010
PhoneGap Talk @ Sencha Con 2010PhoneGap Talk @ Sencha Con 2010
PhoneGap Talk @ Sencha Con 2010
 
Android presentation 2011
Android presentation 2011Android presentation 2011
Android presentation 2011
 
Beginning Android Development
Beginning Android DevelopmentBeginning Android Development
Beginning Android Development
 
Google Developer Group(GDG) DevFest Event 2012 Android talk
Google Developer Group(GDG) DevFest Event 2012 Android talkGoogle Developer Group(GDG) DevFest Event 2012 Android talk
Google Developer Group(GDG) DevFest Event 2012 Android talk
 
Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...
 
2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011
 
Doppl Code Sharing
Doppl Code SharingDoppl Code Sharing
Doppl Code Sharing
 
Dojo Mobile
Dojo MobileDojo Mobile
Dojo Mobile
 
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
 
Flowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDB
 
Building Cross-Platform Mobile Apps
Building Cross-Platform Mobile AppsBuilding Cross-Platform Mobile Apps
Building Cross-Platform Mobile Apps
 
HTML5: Toolkits and Gaps
HTML5: Toolkits and GapsHTML5: Toolkits and Gaps
HTML5: Toolkits and Gaps
 
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
 
Mobile App Testing ScanAgile 2012
Mobile App Testing ScanAgile 2012Mobile App Testing ScanAgile 2012
Mobile App Testing ScanAgile 2012
 
stageTEK5_2016_cisner_w
stageTEK5_2016_cisner_wstageTEK5_2016_cisner_w
stageTEK5_2016_cisner_w
 

Dernier

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Pycon2011 android programming-using_python

  • 1. Android Development using Python + George Goh 10 June 2011 PyCon APAC 1 Friday, June 10, 2011
  • 2. HP Labs Singapore http://www.hpl.hp.com/singapore/ 2 Friday, June 10, 2011
  • 3. Agenda • Android Programming (Java vs. Python) • Python Examples / UI Examples • A More Complex Example 3 Friday, June 10, 2011
  • 4. Android Rocks!!! 4 Friday, June 10, 2011
  • 5. Why Python? 5 Friday, June 10, 2011
  • 6. Programming Android 6 Friday, June 10, 2011
  • 7. Plus Python 7 http://www.blangy.com/Photos.html Friday, June 10, 2011
  • 8. A simple program 8 Friday, June 10, 2011
  • 9. Simple Program in Java package com.spodon.pycon; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.widget.EditText; import android.widget.Toast; public class Demo extends Activity { private EditText mEditText = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Hello!"); builder.setMessage("What is your name?"); mEditText = new EditText(this); builder.setView(mEditText); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(Demo.this, "Cancelled", Toast.LENGTH_SHORT).show(); } }); ... 9 Friday, June 10, 2011
  • 10. Simple Program in Python import android droid = android.Android() name = droid.getInput("Hello!", "What is your name?") droid.makeToast("Hello, %s" % name.result) • Java program: 35 SLOC • Equivalent Python program: 4 SLOC 10 Friday, June 10, 2011
  • 11. Android module import android droid = android.Android() name = droid.getInput("Hello!", "What is your name?") droid.makeToast("Hello, %s" % name.result) • Exposes android functionality via an Android() object. • Talks to a service called SL4A (Scripting Layer for Android). 11 Friday, June 10, 2011
  • 12. Invoking functionality import android droid = android.Android() name = droid.getInput("Hello!", "What is your name?") droid.makeToast("Hello, %s" % name.result) Python Interpreter Android functionality exposed via RPC methods android.py SL4A 12 Friday, June 10, 2011
  • 13. Scripting Layer for Android (SL4A) Search keyword: android-scripting 13 Friday, June 10, 2011
  • 14. Scripting Layer for Android (SL4A) • Started in 2009 by Damon Kohler • 20% time project at Google. • Supports Python, Ruby, Perl, Lua, JavaScript, BeanShell and more. 14 Friday, June 10, 2011
  • 15. Users of SL4A • Rockets • SmallSat 15 http://www.flickr.com/photos/jurvetson/ Friday, June 10, 2011
  • 16. Users of SL4A Cellbots - http://www.cellbots.com 16 http://www.flickr.com/photos/motorbikematt/ Friday, June 10, 2011
  • 17. SL4A Functionality • ActivityResult • MediaRecorder • Android • Phone • ApplicationManager • Preferences • BatteryManager • SensorManager • Camera • Settings • CommonIntents • Sms • Contacts • SpeechRecognition • Event • ToneGenerator • EyesFree • WakeLock • Location • Wifi • MediaPlayer • UI 17 Friday, June 10, 2011
  • 18. Examples Speech Recognition import android droid = android.Android() message = droid.recognizeSpeech("What is your command?") droid.makeToast("You said: %s" % message.result) 18 Friday, June 10, 2011
  • 19. Examples Text-to-Speech import android droid = android.Android() droid.vibrate() droid.ttsSpeak("Hello, this is android speaking!") 19 Friday, June 10, 2011
  • 20. Examples Web View import android droid = android.Android() message = droid.webViewShow("http://xkcd.com/353/") 20 Friday, June 10, 2011
  • 21. Examples SMS import android droid = android.Android() droid.smsSend(someNumber,"Let’s meet for drinks!") 21 Friday, June 10, 2011
  • 22. Dealing with UI 22 Friday, June 10, 2011
  • 23. UI • WebView Frontend (HTML + Javascript) • Python Backend • Frontend talks to Backend using Events 23 Friday, June 10, 2011
  • 24. Events • eventPost(name, data) • eventWaitFor(eventName, timeout) • eventClearBuffer() • eventPoll(number_of_events) • eventWait() 24 Friday, June 10, 2011
  • 25. example.py Example import android droid = android.Android() droid.webViewShow("/sdcard/sl4a/scripts/html/example.html") result = droid.eventWaitFor("EVENT_A").result[“data”] self.droid.log("Received data from EVENT_A: " + result) example.html ... <script language= "javascript" type= "text/javascript"> var droid = new Android(); var date = new Date(); droid.eventPost("EVENT_A", "Page Loaded On " + date); </script> ... 25 Friday, June 10, 2011
  • 26. Before we move on... • What was discussed so far • Using the android.py module in Python programs. • android.py talks to SL4A, which exposes Android functionality to clients. • UI can be built using HTML+Javascript, and it can talk to Python backend using SL4A events. 26 Friday, June 10, 2011
  • 27. A more complete example? 27 Friday, June 10, 2011
  • 28. Control robots! 28 http://www.flickr.com/photos/motorbikematt/ Friday, June 10, 2011
  • 29. The Design direction control Arduino Bluetooth FWD module Cellbots LEFT STOP RIGHT firmware BACK analog motor control 29 Friday, June 10, 2011
  • 30. The Design Arduino Bluetooth module Arduino Cellbots • Cellbots project for firmware firmware • PDE files on Cellbots site Android • FWD LEFT STOP RIGHT HTML + Javascript for frontend UI • BACK Python for backend, Cellbot control • Bluetooth module required (Py4A project) 30 Friday, June 10, 2011
  • 31. Cellbot Controller • Looks for Cellbot devices via Bluetooth. • Connects to a selected device and controls its movement. • Invokes WebView to display UI. • Interacts with UI using SL4A events. Code available at https://github.com/georgegoh/cellbot-controller 31 Friday, June 10, 2011
  • 32. Connecting to the Device cellbot.py 1. Display scan view Start scan.html 2. even t(scanBluetooth) User clicks “Scan” Scan for list of nearby devices 3. event(bluetoothDevicesFound) and post UI shows devices list luetoothDevice) Connect to selected 4. event(connectB User selects device device 32 Friday, June 10, 2011
  • 33. Bluetooth scanning def scan_bluetooth(self, arg): """ Discover nearby Bluetooth devices and trigger an SL4A event "bluetoothDevicesFound" with the list of devices found. """ self.droid.log("Scanning bluetooth devices") self.discovered_devices = bluetooth.discover_devices(lookup_names=True) self.droid.log("Devices found: " + str(self.discovered_devices)) self.droid.eventPost("bluetoothDevicesFound", json.dumps(self.discovered_devices)) Code available at https://github.com/georgegoh/cellbot-controller 33 Friday, June 10, 2011
  • 34. Bluetooth connection def connect_bluetooth_device(self, bd_addr): """ Connect to a Bluetooth device specified by the bd_addr address and display the control view for the device. """ service = bluetooth.find_service(uuid=CELLBOT_UUID, address=bd_addr)[0] self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.socket.connect((service["host"], service["port"])) self.droid.webViewShow(CONTROL_VIEW) Code available at https://github.com/georgegoh/cellbot-controller 34 Friday, June 10, 2011
  • 35. Controlling the Device cellbot.py 1. Display control view Start control.html 2. event(move) User clicks a direction Send direction to connected cellbot 35 Friday, June 10, 2011
  • 36. Motion Control def move(self, direction): """ Move a connected Cellbot in one of the following directions: f - Forward b - Back l - Left r - Right s - Stop """ if self.socket: self.socket.send(direction + "n") Code available at https://github.com/georgegoh/cellbot-controller 36 Friday, June 10, 2011
  • 37. Frontend HTML/JS Control 1 <head>   <title>Robot demo</title>   <script type="text/javascript" src="./js/mootools.js"></script>   <script language="javascript" type="text/javascript">     var droid=new Android();     function postToPython(data) {       droid.eventPost("PYTHON", JSON.stringify(data));     }     function move(direction) {       postToPython({action: "move", data: direction});     }     window.addEvent("domready", function() {       $('bFwd').addEvent('click', function() { move("f"); });       $('bLeft').addEvent('click', function() { move("l"); });       $('bStop').addEvent('click', function() { move("s"); });       $('bRight').addEvent('click', function() { move("r"); });       $('bBack').addEvent('click', function() { move("b"); });       $('bExit').addEvent('click', function() { postToPython ({action:"EXIT", data:""}); });     });   </script> </head> 37 Friday, June 10, 2011
  • 38. Frontend HTML/JS Control 2 <body>   <table align=center>     <tr>       <td />       <td align=center><button id="bFwd">FWD</button></td>       <td />     </tr>     <tr>       <td align=center><button id="bLeft">LEFT</button></td>       <td align=center><button id="bStop">STOP</button></td>       <td align=center><button id="bRight">RIGHT</button></td>     </tr>     <tr>       <td />       <td align=center><button id="bBack">BACK</button></td>       <td />     </tr>   </table>   <button id="bExit">EXIT</button> </body> 38 Friday, June 10, 2011
  • 39. Python for Android (Py4A) • Additional python modules added: - Bluez, Twisted, Zope, pyEphem • Current maintainers: - Naranjo Manuel Francisco - Robbie Matthews 39 Friday, June 10, 2011
  • 40. References • Scripting Layer for Android http://code.google.com/p/android-scripting • Python for Android http://code.google.com/p/python-for-android • In Love with a Droid http://android-scripting.blogspot.com/ • Cellbots http://www.cellbots.com 40 Friday, June 10, 2011
  • 41. Acknowledgements • Damon Kohler • Robbie Matthews • Colleagues @ HP Labs Singapore 41 Friday, June 10, 2011
  • 42. ? 42 Friday, June 10, 2011
  • 43. Thank you @georgegoh https://github.com/georgegoh/ http://www.linkedin.com/in/georgegoh 43 Friday, June 10, 2011
  • 44. fin 44 Friday, June 10, 2011
  • 45. Bonus/Misc Slides 45 Friday, June 10, 2011
  • 46. Event loop while action != "EXIT": self.droid.log("Python: Waiting for event.") event_data = self.droid.eventWaitFor("PYTHON").result["data"] self.droid.log("Python: Event received. Processing...") # unpack the event data and perform action(if available). properties = json.loads(event_data) self.droid.log("Result: " + str(properties)) action = properties["action"] if action in self.handlers: self.handlers[action](properties["data"]) Code available at https://github.com/georgegoh/cellbot-controller 46 Friday, June 10, 2011
  • 47. Packaging your app • Download the template project archive • http://android-scripting.googlecode.com/hg/android/ script_for_android_template.zip • Modify the following according to your project • Import into Eclipse • Refactor package name from com.dummy.fooforandroid to your package name. • Modify or put your script into the res/raw directory. • http://code.google.com/p/android-scripting/wiki/SharingScripts 47 Friday, June 10, 2011
  • 48. How SL4A works • Android functionality is abstracted into methods. • These methods are grouped in subsystems called ‘Facades’. • A JSON-RPC server exposes the methods contained in these Facades. 48 Friday, June 10, 2011
  • 49. SL4A Architecture Facade 0 . Client functionality exposed via RPC methods FacadeManager . . JsonRpcServer Facade N 49 Friday, June 10, 2011
  • 50. Facades • A facade represents a collection of functionality RPCReceiver • @Rpc annotation <<implements>> exposes methods XYZFacade • @RpcParameter, <<Rpc>> + doIt() @RpcDefault, @RpcOptional describe method arguments. 50 Friday, June 10, 2011
  • 51. Facades public void dialogCreateInput(final String title, final String message, final String text) throws InterruptedException { dialogDismiss(); mDialogTask = new AlertDialogTask(title, message); ((AlertDialogTask) mDialogTask).setTextInput(text); } Common/src/com/googlecode/android_scripting/facade/ui/UIFacade.java public class UiFacade extends RpcReceiver { RpcReceiver is the abstract [...] parent of all Facade classes @Rpc(description = "Create a text input dialog.") @Rpc annotation to indicate public void dialogCreateInput( method is exposed via RPC @RpcParameter(name = "title", description = "title of the input box") @RpcDefault("Value") final String title, @RpcParameter(name = "message", description = "message to display above the input box") @RpcDefault("Please enter value:") final String message, @RpcParameter(name = "defaultText", description = "text to insert into the input box") @RpcOptional final String text) throws InterruptedException { used in @RpcParameter dialogDismiss(); generating user-readable Default values can be descriptions mDialogTask = new AlertDialogTask(title, message); specified using the ((AlertDialogTask) mDialogTask).setTextInput(text); @RpcDefault annotation } [...] } 51 Friday, June 10, 2011
  • 52. Code details For details, see: • AndroidProxy • FacadeManagerFactory • FacadeManager • FacadeConfiguration 52 Friday, June 10, 2011
  • 53. Facades http://code.google.com/p/android-scripting/wiki/ApiReference 53 Friday, June 10, 2011
  • 54. Remote Control • Write programs using your computer keyboard and monitor and control an Android device remotely. • Start a SL4A server on your Android, export some environment variables and import the “android.py” module. • http://bit.ly/startpy4a 54 http://xkcd.com/722/ Friday, June 10, 2011
  • 55. SL4A Architecture Language Interpreter Facade 0 . functionality exposed via RPC methods FacadeManager . Language . specific library JsonRpcServer Facade N 55 Friday, June 10, 2011
  • 56. What you need • On your dev machine • Android SDK • Python 2.6 • On your Android • Barcode Scanner 56 Friday, June 10, 2011
  • 57. If you don’t have a barcode scanner 1. Start the Android Market App. 2. Search for pub: “ZXing Team” 3. Install “Barcode Scanner” 57 Friday, June 10, 2011
  • 58. So I’ve installed SL4A and Py4A. What’s next? 58 Friday, June 10, 2011
  • 59. Install more... • Py4A is not the Python environment. • It is the manager for the Python interpreter, extras, and scripts. • Extras => libraries • Scripts => sample python scripts to get you started. 59 Friday, June 10, 2011
  • 60. Install the env • Start “Python for Android” • Click “Install” 60 Friday, June 10, 2011