Advertisement
Advertisement

More Related Content

Slideshows for you(20)

Similar to Python on Android(20)

Advertisement

Python on Android

  1. Python on Android 정보기술 시대에 유익한 파이썬 프로그래밍 – 제 10 강 (2) 동양미래대학교 2015.7 최용 <sk8er.choi@gmail.com>
  2. 주제 • Scripting Layer for Android (SL4A) 소개 • Android 실습 환경 준비 • SL4A와 Python (or QPython) 설치 • Python Shell 실습 • Python Script 실습
  3. Scripting Layer for Android (SL4A) 소개
  4. Scripting Layer for Android (SL4A) 소개 • Android에서 다양한 스크립트를 실행할 수 있도록 하는 라이브러리 • Google의 20% 프로젝트로 시작 • ASE(Android Scripting Environment)에서 SL4A(Scripting Layer for Android)로 명칭 변경 • 실험적인 구현임 • 여러 스크립트 언어를 사용할 수 있음 • Python (CPython) • Perl • Ruby • Lua • … • https://code.google.com/p/android-scripting/ (closed) • https://github.com/damonkohler/sl4a • https://github.com/kuri65536/sl4a (forked)
  5. SL4A Architecture Android Operating Platform (Dalvik VM) Scripting Layer for Android (SL4A) import android droid = android.Android() text = "Hello toast!" droid.makeToast(text) hello.py Hello toast! Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();
  6. SL4A Architecture Android Operating Platform (Dalvik VM) Scripting Layer for Android (SL4A) Client (Python) SL4A RPC Server (Android Java Application) Client (Perl) Client (Lua) …
  7. SL4A AndroidProxy & Façades AndroidProxy Android Operating Platform TextToSpeechFaçade SmsFaçade class Android(object): def _rpc(self, method, *args): data = {'id': self.id, 'method': method,'params': args} request = json.dumps(data) response = self.client.readline() result = json.loads(response) return Result(id=result['id'], result=result['result'], error=result['error'], ) android.py @Rpc(description = "Displays a short-duration Toast notification.") public void makeToast(@RpcParameter(name = "message") final String message) { mHandler.post(new Runnable() { public void run() { Toast.makeText(mService, message, Toast.LENGTH_SHORT).show(); } }); } AndroidFacade.java Android API CameraFaçade AndroidFaçade JSON, RPC
  8. Android 실습 환경 준비
  9. 실습 환경 비교 SL4A + Py4A (apk 설치) QPython / QPython3 (Play 스토어) actual Android Phone 좋음 (설치 번거로움) Best! virtual Android Emulator 절반의 성공 (= FAIL = 삽질) Not tested (Play 스토어?) VMWare(or VirtualBox) + android-x86 Not tested Not tested BlueStacks Not tested (apk 설치?) 좋음 (설치와 사용 편리. SL4A 오류 발생 )
  10. Android 실습 환경 준비 • #1 안드로이드 폰 또는 • PC 상의 가상(Virtual) 환경 • #2 안드로이드 에뮬레이터(Android Studio에 포함) 또는 • #3 VMWare + android-x86 또는 • #4 BlueStacks App Player
  11. #1 Android Phone
  12. #2 Android Emulator • Java Development Kit (JDK) 설치 http://www.oracle.com/technetwork/java/javase/downloads/index.html • Android Studio • 다운로드 및 설치 https://developer.android.com/sdk/index.html • Virtual Device 생성 • SD 카드 사용 설정 %HOME%.androidavd<장치 이름>config.ini 파일 hw.sdCard=yes 로 변경
  13. #3 android-x86 • 하이퍼바이저 • VMWare Player https://www.vmware.com/go/downloadplayer • VirtualBox https://www.virtualbox.org/wiki/Downloads • Android-x86 http://www.android-x86.org/ • Live CD • Installation http://visualgdb.com/tutorials/android/vmware/ 참고 • Pre-installed Image http://www.mininova.org/tor/13278096/
  14. #4 BlueStacks App Player • 안드로이드 앱을 PC(Win, Mac)에서 사용할 수 있는 가상 환경 • 무료 설치, 월 사용료를 지불하거나 스폰서 앱 설치 • http://www.bluestacks.com/download.html
  15. SL4A와 Python (or QPython) 설치
  16. SL4A와 Python (or QPython) 설치 • #1 SL4A와 Python 설치 • SL4A • https://github.com/kuri65536/sl4a/releases에서 sl4a-r6x05-x86-debug.apk 다운로드하여 설치하거나, • Android SDK의 adb 사용하여 설치 가능 > cd %HOME%AppDataLocalAndroidsdkplatform-tools > adb install "%HOME%"Downloadssl4a-r6x05-x86-debug.apk • Python-for-android • https://code.google.com/p/python-for-android/downloads/ 에서 Python3ForAndroid_r6.apk 다운로드하여 설치하거나, • > adb install "%HOME%"DownloadsPython3ForAndroid_r6.apk • 폰에서 “Python3 for Android” 실행 – Install 터치 또는 • #2 Play 스토어에서 QPython 설치
  17. Qpython – Python on Android • Python 2(QPython) & 3(QPython3) • 콘솔(Shell) • 편집기 • QPyPi http://qpython.com/
  18. Hello, Android! 1. Start button 2. Run script 3. hello_world.py
  19. Python Shell 실습
  20. QPython – Console 콘솔 추가로 열기 설정 콘솔 창 선택
  21. makeToast() >>> import android >>> droid = android.Android() >>> droid.makeToast("Hello") Result(id=1, result=None, error=None) • SL4A API 호출 결과(Result) • id 숫자값, 처음 호출하면 1, 호출할 때마다 1씩 증가 • result API 호출 결과. 값이 있으면 JSON 형식으로, 값이 없으면 null(None) • error 오류 발생 내역. 오류가 없으면 null(None)
  22. vibrate() >>> droid.vibrate() Result(id=2, result=None, error=None)
  23. getLaunchableApplications() >>> droid.getLaunchableApplications() Result(id=3, result={'Swift HD Camera': 'com.stark.gadgets.swift.hd.camera. CameraActivity', 'SetupWizard': 'com.bluestacks.setup.SetupWizardActivity', ... }, error=None) >>> import pprint >>> apps = droid.getLaunchableApplications() >>> pprint.pprint(apps.result) {'1Mobile Market': 'me.onemobile.android.LaunchActivity', 'AppFinder': 'com.bluestacks.appfinder.AppFinder', 'AppSettings': 'com.bluestacks.appsettings.Main', ... '트위터': 'com.twitter.android.StartActivity'}
  24. Python Script 실습
  25. QPython – Editor (QEdit) 들여쓰기 행 번호로 이동 저장 다른 이름으로 저장 undo 실행 찾기 옵션 Snippets 최근 파일 열기 들여쓰기 열기 새 파일
  26. QPython – Scripts • Scripts • Projects
  27. 샘플 스크립트 – hello_world.py import sl4a droid = sl4a.Android() droid.makeToast('Hello, Android!') print('Hello world!') Toast: 작은 팝업으로서 나타나는 간단한 피드백 http://developer.android.com/guide/topics/ui/notifiers/toasts.html
  28. 샘플 스크립트 – take_picture.py import sl4a droid = sl4a.Android() droid.cameraInteractiveCapturePicture('/sdcard/qpython.jpg')
  29. 샘플 스크립트 – say_time.py import sl4a import time droid = sl4a.Android() droid.ttsSpeak(time.strftime("%I %M %p on %A, %B %e, %Y")) %I Hour (12-hour clock) as a zero-padded decimal number. %M Minute as a zero-padded decimal number. %p Locale’s equivalent of either AM or PM. %A Weekday as locale’s full name. %B Month as locale’s full name. %e day of the month (1 to 31) %Y Year with century as a decimal number.
  30. httpserver.py try: import SimpleHTTPServer as server # for Python 2 except: import http.server as server # for Python 3 import os os.chdir('/sdcard/') server.test(HandlerClass=server.SimpleHTTPRequestHandler) http://tututen.hatenablog.jp/entry/2014/01/09/121428 참고
  31. httpserver.py 실행 결과 웹 브라우저에서 http://0.0.0.0:8000/ GET
  32. httpserver.py 실행 결과 (index.html) <html> <head> <title>Hello</title> </head> <body> Welcome to my phone! </body> </html>
  33. And More … • 책 바코드 찍어서 검색하기 https://www.mattcutts.com/blog/android-barcode-scanner/ • Random joke 가져와서 친구들에게 문자 메시지 보내기 http://h3manth.com/content/sms-android-using-python • 약정 벗은 안드로이드, 서버가 되다 http://www.zdnet.co.kr/column/column_view.asp?artice_id=201 20518070549
  34. 참고 자료 • 웹사이트 • https://github.com/damonkohler/sl4a • https://code.google.com/p/python-for-android/ • https://groups.google.com/forum/#!forum/android-scripting • http://wiki.qpython.org/doc/ • SL4A API Help http://www.mithril.com.au/android/doc/ • Android applications using Python and SL4A http://www.ibm.com/developerworks/library/mo-python-sl4a-1/ • 책 • Lucas Jordan 외, Practical Android Projects, Apress • Paul Ferrill 저, 류광 역, 프로 안드로이드 SL4A: 파이썬으로 안드로이드 앱 만 들기, 와우북스

Editor's Notes

  1. 한글 설정: Play 스토어에서 Google 한국어 입력기 설치 (Google 계정 입력 필요) IME 선택에서 한글 키보드 사용
Advertisement