This book is about writing real-world applications for the Android platform primarily using the Python language and a little bit of JavaScript. While there is nothing wrong with Java, it really is overkill when all
you need to do is turn on or off a handful of settings on your Android device. The Scripting Layer for Android (SL4A) project was started to meet that specific need. This book will introduce you to SL4A and
give you the power to automate your Android device in ways you never thought possible. html
本書是關於用Python和一點Javascript來開發Android。Java開發合情,當你只用來修改你的安卓設備的設置時,用這個有點小題大做了。 SL4A正是作這個特殊應用的。本書將你帶領到SL4A,而且給你強大的自動化你的設備的能力,是你之前所認爲不可能的。
Why SL4A?
One of the first questions you probably have about this book is, 「Why would I want to use SL4A instead of Java?」 There are several answers to that question. One is that not everyone is a fan of Java. The Java language is too heavyweight for some and is not entirelyopen source. It also requires the use of an edit / compile / run design loop that can be tedious for simple applications. An equally legitimate answer is simply 「I want to use X」, where X could be any number of popular languages. android
爲何用? 不是全部人都是JAVA開發。它語言太龐大無沒徹底開源,須要編譯。你能夠須要一個其它的開發語言
Google provides a comprehensive software development kit (SDK) aimed specifically at Java developers, and most applications available from the Android market are probably written in Java. I’ll address the Android SDK in Chapter 3 and use a number of the tools that come with it throughout the
book. git
Google的SDK是針對Java開發人員,安卓市場上多數了是Java開發。第3章我會講SDK而且自始至終會用到一些它 的工具。
SL4A當前支持如下語言:Beanshell, JRuby, Lua, Perl, PHP, Python, and Rhino. web
SL4A is really targeted at anyone looking for a way to write simple scripts to automate tasks on an Android device using any of the supported languages, including Java through Beanshell. It provides an interactive console in which you can type in a line ofcode and immediately see the result. It even makes it possible, in many cases, to reuse code you’ve written for a desktop environment. The bottom line is that SL4A makes it possible both to write code for Android-based devices in languages other than Java and to do it in a more interactive way. shell
SL4A是針對全部想寫腳本去完成自動化任務的人,它提供一個交互控制檯。它使在安卓類的設備上用其它語言開發及交互的方法。
CHAPTER 1 ■INTRODUCTION
2
The World of Android
Google jumped into the world of mobile operating systems in a big way when it bought Android, Inc. in
2005. It’s really pretty amazing how far it has come in such a short time. The Android community is huge
and has spawned a wide range of conferences, books, and support materials that are easily available
over the Internet. express
安卓世界windows
2005年,Google買了安卓,並進入到移動系統開發領域。發展這麼快是個奇蹟。安卓社區在快速增加。
This is a good point to define a few terms that you’ll see throughout the rest of this book. Android
applications are typically packaged into .apkfiles. These are really just .zipfiles containing everything
needed by the application. In fact, if you rename an .apkfile to .zip,you can open it with any archive
tool and examine the contents. 安全
.APK文件 就是一個.zip文件,你能夠查看它的內容。
Most Android devices come from the manufacturer with the systems files protected to prevent any
inadvertent or malicious manipulation. The Android operating system (OS) is essentially Linux at the
core and provides much of the same functionality you would find on any Linux desktop. There are ways
to unlock the system areas and provide root, or unrestricted, access to the entire filesystem on an
Android device. This process is appropriately called rootingyour device, and once complete, the device
is described as rooted. SL4A does not require a rooted device, but will work on one if you have chosen
this path. 網絡
安卓設備默認是阻止修改系統文件。安卓OS是基礎Linux,有不少功能你能在Linux桌面系統中找到相似的。你能夠經過Root來獲取所有功能。app
SL4A不須要你使用一個Root過的設備。
Android Application Anatomy
Android is based on the Linux operating system (at the time of writing, version 2.6 of the Linux kernel).
Linux provides all the core plumbing such as device drivers, memory and process management, network
stack, and security. The kernel also adds a layer ofabstraction between the hardware and applications.
To use an anatomical analogy, you might think of Linux as the skeleton, muscles, and organs of the
Android body.
安卓應用分析
安卓基於Linux,LInux已經提供了設備的驅動,內存、進程、網絡、安全等管理。Linux是安卓系統的骨架,肌肉和器官。
The next layer up the Android stack is the Dalvik Virtual Machine (DVM). This piece provides the
core Java language support and most of the functionality of the Java programming language. The DVM is
the brains in which the majority of all processing takes place. Every Android application runs in its own
process space in a private instance of the DVM. The application framework provides all the necessary
components needed by an Android application. From the Google Android documentation:
「Developers have full access to the same framework APIs used by the core applications.
The a pplication ar chitecture is des igned to sim plify the r euse o f com ponents. Any
application can publi sh it s ca pabilities, and any other a pplication may th en make
use o f tho se capabilities (subject to security constraints enf orced by the fr amework).
This same mechanism allows components to be replaced by the user.
下一包裝層是DVM,它提供Java語言支持。它是全部進程最主要運行的地方,是大腦。全部安卓程序運行在一個Dvm的私有實例上。
安卓開發框架提供全部必須組件。安卓文檔說:開發都經過同一個框架API.應用框架的設計是爲了簡化和重用組件。任何應用能夠
發佈功能,其它程序可使用這些功能(固然要受到框架的安全約束)。一樣的機制可讓用戶替代某些組件。
Underlying all applications is a set ofservices and systems, including:
• A rich and e xtensible s et of Views th at can be used to build an ap plication,
including lis ts, grids, tex t boxes, butt ons, and ev en an emb eddable w eb
browser
• Content Pr oviders that enable a pplications to a ccess dat a f rom other
applications (such as Contacts) or to share their own data
• A Resource Manager, pr oviding access to non-code resources such as localized
strings, graphics, and layout files
CHAPTER 1 ■INTRODUCTION
3
• A Notif ication Manager t hat enables all applications to display custom alerts
in the status bar
• An Activity Manager that manages the lifecycle of applications and provides a
common navigation backstack」
1
All Android applications are based on three core components: activities, services, and receivers.
These core components are activated through messages called intents. SL4A gives you access to much of
the core Android functionality through its API facade, so it’s a good idea to understand some of the
basics. Chapters 3 and 5 look at the Android SDK and Android application programming interface (API)
in detail, so I’ll save the specifics for later. For now, I’ll introduce you to activities and intents, as they will
be used extensively.
Activities
The Android documentation defines an activityas 「an application component that provides a screen
with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window
typically fills the screen but may be smaller thanthe screen and float on top of other windows.」
Android applications consist of one or more activities loosely coupled together. Each application
will typically have a 「main」 activity that can, in turn, launch other activities to accomplish different
functions.
Intents
From the Google documentation: 「An intent is a simple message object that represents an intentionto
do something. For example, if your application wants to display a web page, it expresses its intentto
view the URI by creating an intent instance and handing it off to the system. The system locates some
other piece of code (in this case, the browser) that knows how to handle that intent and runs it. Intents
can also be used to broadcast interesting events (such as a notification) system-wide.」
An intent can be used with startActivityto launch an activity, broadcastIntentto send it to any
interested BroadcastReceivercomponents, and startService(Intent)or bindService(Intent,
ServiceConnection, int)to communicate with a backgroundservice. Intents use primary and
secondary attributes that you must provide in the form of arguments.
There are two primary attributes:
• action:The general action to be performed, such as VIEW_ACTION, EDIT_ACTION,
MAIN_ACTION, and so on
• data:The data to operate on, such as a person record in the contacts database,
expressed as a Uniform Resource Identifier (URI)
1
http://developer.android.com/guide/basics/what-is-android.html
CHAPTER 1 ■INTRODUCTION
4
There are four types of secondary attributes:
• category:Gives additional information about the action to execute. For example,
LAUNCHER_CATEGORYmeans it should appear in the Launcher as a top-level
application, while ALTERNATIVE_CATEGORYmeans it should be included in a list of
alternative actions the user can perform on a piece of data.
• type:Specifies an explicit type (a MIME type) of the intent data. Normally, the
type is inferred from the data itself. By setting this attribute, you disable that
evaluation and force an explicit type.
• component:Specifies an explicit name of a component class to use for the intent.
Normally this is determined by looking at the other information in the intent (the
action, data/type, and categories) and matching that with a component that can
handle it. If this attribute is set, none of the evaluation is performed, and this
component is used exactly as is. By specifying this attribute, all the other intent
attributes become optional.
• extras:A bundle of any additional information. This can be used to provide
extended information to the component. For example, if we have an action to
send an e-mail message, we could also include extra pieces of data here to supply
a subject, body, and so on.
SL4A History
SL4A was first announced on the Google Open Sourceblog in June of 2009 and was originally named
Android Scripting Environment (ASE).It was primarily through the efforts of Damon Kohler that this
project came to see the light of day. Others have contributed along the way as the project has continued
to mature. The most recent release as of this writing isr4, although you’ll also find experimental versions
available on the SL4A web site (http://code.google.com/p/android-scripting). SL4A Architecture At its lowest level, SL4A is essentially a scriptinghost, which means that as an application it hosts different interpreters each of which processes a specific language. If you were tobrowse the SL4A source code repository, you would see a copy of the source tree of each language. This gets cross-compiled for the ARM architecture using the Android Native Development Kit (NDK) and loads as a library when SL4A launches a specific interpreter. At that point,the script will be interpreted line by line. The basic architecture of SL4A is similar to what you would see in a distributed computing environment. Figure 1-1 shows in pictorial form the flow of execution when you launch SL4A and then run a script (in this case, hello.py). Every SL4A script must import or source an external file, such as android.pyfor Python, which will define a number of proxy functions needed to communicate with the Android API. The actual communication between SL4A and the underlying Android operating system uses a remote procedure call (RPC) mechanism and JavaScript Object Notation (JSON). You normally find RPC used in a distributed architecture in which information is passed between a client and a server. In the case of SL4A, the server is the Android OS, and the clientis an SL4A script. This adds a layer of separation between SL4A and the Android OS to prevent any malicious script from doing anything harmful. CHAPTER 1 ■INTRODUCTION 5 Security is a concern and is one of the reasons that SL4A uses the RPC mechanism. Here’s how the SL4A wiki describes it: 「RPC Authentication: SL4A enforces per-script security sandboxing by requiring all scripts t o be authenti cated by the corresponding RPC server. In ord er for the authentication to succ eed, a script has to send the corr ect hand shake se cret to th e corresponding server. This is accomplished by: 1. reading the AP_HANDSHAKEenvironment variable. 2. calling th e RPC me thod _authenticatewith the value of AP_HANDSHAKEas an argument. The _authenticatemethod must be the fi rst RPC call and should take place during the initialization of the Andr oid library. F or example, see Rhin o’s o r Python’s A ndroid module」.2Figure 1-1.SL4A execution flow diagra