주제• Scripting Layer for Android (SL4A) 소개• Android 실습 환경 준비• SL4A 와 Python (or QPython) 설치• Python Shell 실습• Python Script 실습
Scripting Layer for Android (SL4A) 소개
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)
SL4A Architecture
Android Operating Platform(Dalvik VM)
Scripting Layer for Android(SL4A)
import androiddroid = 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();
SL4A Architecture
Android Operating Platform(Dalvik VM)
Scripting Layer for Android (SL4A)Client(Pytho
n)
SL4A RPC Server(Android Java Application)
Client(Perl)
Client(Lua)
…
SL4
A
AndroidProxy & Façades
AndroidProxy
Android Operating Platform
TextToSpeechFaçadeSmsFaç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
Android 실습 환경 준비
실습 환경 비교SL4A + Py4A
(apk 설치 )QPython / QPython3
(Play 스토어 )
actual Android Phone 좋음( 설치 번거로움 )
Best!
virtual Android Emulator 절반의 성공(= FAIL = 삽질 )
Not tested(Play 스토어 ?)
VMWare(or Virtual-Box)
+ android-x86
Not tested Not tested
BlueStacks Not tested(apk 설치 ?)
좋음( 설치와 사용 편리 .SL4A 오류 발생 )
Android 실습 환경 준비• #1 안드로이드 폰
또는• PC 상의 가상 (Virtual) 환경• #2 안드로이드 에뮬레이터 (Android Studio 에 포함 )
또는• #3 VMWare + android-x86
또는• #4 BlueStacks App Player
#1 Android Phone
#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%\.android\avd\< 장치 이름 >\config.ini 파일hw.sdCard=yes 로 변경
#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/
#4 BlueStacks App Player
• 안드로이드 앱을 PC(Win, Mac) 에서 사용할 수 있는 가상 환경• 무료 설치 , 월 사용료를 지불하거나 스폰서 앱 설치• http://www.bluestacks.com/download.html
SL4A 와 Python (or QPython) 설치
SL4A 와 Python (or QPython) 설치• #1 SL4A 와 Python 설치
• SL4A• https://github.com/kuri65536/sl4a/releases에서
sl4a-r6x05-x86-debug.apk 다운로드하여 설치하거나 ,• Android SDK 의 adb 사용하여 설치 가능
> cd %HOME%\AppData\Local\Android\sdk\platform-tools\> adb install "%HOME%"\Downloads\sl4a-r6x05-x86-debug.apk
• Python-for-android• https://code.google.com/p/python-for-android/downloads/ 에서
Python3ForAndroid_r6.apk 다운로드하여 설치하거나 ,• > adb install "%HOME%"\Downloads\Python3ForAndroid_r6.apk
• 폰에서 “ Python3 for Android” 실행 – Install 터치또는
• #2 Play 스토어에서 QPython 설치
Qpython – Python on Android
• Python 2(QPython) & 3(QPython3)• 콘솔 (Shell)• 편집기• QPyPi
http://qpython.com/
Hello, Android!
1. Start button2. Run script 3. hello_world.py
Python Shell 실습
QPython – Console
콘솔 추가로 열기
설정
콘솔 창 선택
makeToast()
>>> import android
>>> droid = android.Android()
>>> droid.makeToast("Hello")
Result(id=1, result=None, error=None)
• SL4A API 호출 결과 (Result)• id
숫자값 , 처음 호출하면 1,호출할 때마다 1 씩 증가
• resultAPI 호출 결과 .값이 있으면 JSON 형식으로 ,값이 없으면 null(None)
• error오류 발생 내역 .오류가 없으면 null(None)
vibrate()
>>> droid.vibrate()
Result(id=2, result=None, error=None)
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'}
Python Script 실습
QPython – Editor (QEdit)
들여쓰기
행 번호로 이동
저장
다른 이름으로 저장
undo
실행
찾기
옵션
Snip-pets
최근 파일 열기
들여쓰기
열기
새 파일
QPython – Scripts
• Scripts • Projects
샘플 스크립트 – 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
샘플 스크립트 – take_picture.py
import sl4a
droid = sl4a.Android()
droid.cameraInteractiveCapturePicture('/sdcard/qpython.jpg')
샘플 스크립트 – 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.
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 참고
httpserver.py 실행 결과웹 브라우저에서 http://0.0.0.0:8000/ GET
httpserver.py 실행 결과 (index.html)
<html>
<head>
<title>Hello</title>
</head>
<body>
Welcome to my phone!
</body>
</html>
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=20120518070549
참고 자료• 웹사이트
• 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: 파이썬으로 안드로이드 앱
만들기 , 와우북스