SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

Python for the C# developer
Python for the C# developerPython for the C# developer
Python for the C# developer
Michael 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 presentation
Kavi 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 Python
jbrendel
 
Python games
Python gamesPython games
Python games
molw
 
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 Heroku
codeheroku
 
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
Sarah Walsh
 
Django
DjangoDjango
Django
Momentum Design Lab
 
GCE 上搭配 Cloud Storage 建置 Drone CI
 GCE 上搭配 Cloud Storage 建置 Drone CI GCE 上搭配 Cloud Storage 建置 Drone CI
GCE 上搭配 Cloud Storage 建置 Drone CI
MING JUI Chen
 
Pyconza(2)
Pyconza(2)Pyconza(2)
Pyconza(2)
Nanjekye Joannah
 
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 Conference
Frances 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 Usefulness
Python UsefulnessPython Usefulness
Python Usefulness
Vipul Petkar
 
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
masukmia.com
 
Python for beginners
Python for beginnersPython for beginners
Python for beginners
Ananda Kumar HN
 
The Awesomeness of Go
The Awesomeness of GoThe Awesomeness of Go
The Awesomeness of Go
Christina Rasimus
 
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 IDEs
Benishchoco
 
Python for the C# developer
Python for the C# developerPython for the C# developer
Python for the C# developer
Michael 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 presentation
Kavi 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 Python
jbrendel
 
Python games
Python gamesPython games
Python games
molw
 
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 Heroku
codeheroku
 
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
Sarah Walsh
 
GCE 上搭配 Cloud Storage 建置 Drone CI
 GCE 上搭配 Cloud Storage 建置 Drone CI GCE 上搭配 Cloud Storage 建置 Drone CI
GCE 上搭配 Cloud Storage 建置 Drone CI
MING 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 Conference
Frances 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 tutorial
masukmia.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 IDEs
Benishchoco
 

Viewers also liked (9)

Python for Android
Python for AndroidPython for Android
Python for Android
phlax
 
Workshop Python para Android
Workshop Python para AndroidWorkshop Python para Android
Workshop Python para Android
Rafael Sanches
 
Desenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em PythonDesenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em Python
Relsi 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 facades
Khadime Dramé
 
Python PPT
Python PPTPython PPT
Python PPT
Edureka!
 
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
Sang-ho Choi
 
Facade légére 02
Facade légére 02Facade légére 02
Facade légére 02
Sami Sahli
 
Facade légére 01
Facade légére 01Facade légére 01
Facade légére 01
Sami Sahli
 
Murs de façade
Murs de façadeMurs de façade
Murs de façade
Sami Sahli
 
Python for Android
Python for AndroidPython for Android
Python for Android
phlax
 
Workshop Python para Android
Workshop Python para AndroidWorkshop Python para Android
Workshop Python para Android
Rafael Sanches
 
Desenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em PythonDesenvolvendo aplicações Mobile em Python
Desenvolvendo aplicações Mobile em Python
Relsi 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 facades
Khadime Dramé
 
Python PPT
Python PPTPython PPT
Python PPT
Edureka!
 
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
Sang-ho Choi
 
Facade légére 02
Facade légére 02Facade légére 02
Facade légére 02
Sami Sahli
 
Facade légére 01
Facade légére 01Facade légére 01
Facade légére 01
Sami Sahli
 
Murs de façade
Murs de façadeMurs de façade
Murs de façade
Sami Sahli
 
Ad

Similar to Pycon2011 android programming-using_python (20)

Android Scripting
Android ScriptingAndroid Scripting
Android Scripting
Juan Gomez
 
2011 android
2011 android2011 android
2011 android
vpedapolu
 
Mobile Application development
Mobile Application developmentMobile Application development
Mobile Application development
MIT Autonomous Aurangabad
 
Android developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftwareAndroid developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftware
Romin Irani
 
Android presentation 2011
Android presentation 2011Android presentation 2011
Android presentation 2011
Bram Vandeputte
 
2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon
ikailan
 
Intro to Android Development by Philip Peng
Intro to Android Development by Philip PengIntro to Android Development by Philip Peng
Intro to Android Development by Philip Peng
pennappsmobile
 
Introduction to Android
Introduction to AndroidIntroduction to Android
Introduction to Android
Jesse Anderson
 
Jaime Blasco & Pablo Rincón - Lost in translation: WTF is happening inside m...
Jaime Blasco & Pablo Rincón -  Lost in translation: WTF is happening inside m...Jaime Blasco & Pablo Rincón -  Lost in translation: WTF is happening inside m...
Jaime Blasco & Pablo Rincón - Lost in translation: WTF is happening inside m...
RootedCON
 
Wtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_publicWtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_public
Jaime Blasco
 
Android presentation
Android presentationAndroid presentation
Android presentation
hussainghoto
 
Beginning Android Development
Beginning Android DevelopmentBeginning Android Development
Beginning Android Development
José Ferreiro
 
Android platform
Android platformAndroid platform
Android platform
maya_slides
 
Build Apps
Build AppsBuild Apps
Build Apps
Victor Miclovich
 
Android Development Slides
Android Development SlidesAndroid Development Slides
Android Development Slides
Victor Miclovich
 
Introduction to Android Development and Security
Introduction to Android Development and SecurityIntroduction to Android Development and Security
Introduction to Android Development and Security
Kelwin Yang
 
Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011
ikailan
 
Day1 what is android(print)
Day1 what is android(print)Day1 what is android(print)
Day1 what is android(print)
Dongchul Shin
 
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
ikailan
 
Embedded Android Workshop with Lollipop
Embedded Android Workshop with LollipopEmbedded Android Workshop with Lollipop
Embedded Android Workshop with Lollipop
Opersys inc.
 
Android Scripting
Android ScriptingAndroid Scripting
Android Scripting
Juan Gomez
 
2011 android
2011 android2011 android
2011 android
vpedapolu
 
Android developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftwareAndroid developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftware
Romin Irani
 
Android presentation 2011
Android presentation 2011Android presentation 2011
Android presentation 2011
Bram Vandeputte
 
2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon
ikailan
 
Intro to Android Development by Philip Peng
Intro to Android Development by Philip PengIntro to Android Development by Philip Peng
Intro to Android Development by Philip Peng
pennappsmobile
 
Introduction to Android
Introduction to AndroidIntroduction to Android
Introduction to Android
Jesse Anderson
 
Jaime Blasco & Pablo Rincón - Lost in translation: WTF is happening inside m...
Jaime Blasco & Pablo Rincón -  Lost in translation: WTF is happening inside m...Jaime Blasco & Pablo Rincón -  Lost in translation: WTF is happening inside m...
Jaime Blasco & Pablo Rincón - Lost in translation: WTF is happening inside m...
RootedCON
 
Wtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_publicWtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_public
Jaime Blasco
 
Android presentation
Android presentationAndroid presentation
Android presentation
hussainghoto
 
Beginning Android Development
Beginning Android DevelopmentBeginning Android Development
Beginning Android Development
José Ferreiro
 
Android platform
Android platformAndroid platform
Android platform
maya_slides
 
Android Development Slides
Android Development SlidesAndroid Development Slides
Android Development Slides
Victor Miclovich
 
Introduction to Android Development and Security
Introduction to Android Development and SecurityIntroduction to Android Development and Security
Introduction to Android Development and Security
Kelwin Yang
 
Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011
ikailan
 
Day1 what is android(print)
Day1 what is android(print)Day1 what is android(print)
Day1 what is android(print)
Dongchul Shin
 
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
ikailan
 
Embedded Android Workshop with Lollipop
Embedded Android Workshop with LollipopEmbedded Android Workshop with Lollipop
Embedded Android Workshop with Lollipop
Opersys inc.
 
Ad

Recently uploaded (20)

Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 

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