PDF 格式资源下载:http://download.csdn.net/source/847840
Android Learning Notes
Part I – Android Architecture & Basics
-- By Simon He
-- Last revised on Dec 08, 2008
1. Android Platform Architecture
<Android SDK Installation Folder>/docs/what-is-android.html
1) Android platform layers
l Applications Layer
All applications are equal under the control of Android OS, including phone call, phonebook, and integrated Browser (based on open-sourced WebKit engine).
l Application Framework Layer
This layer can be reused and replaced by different OEM company like MOTO.
l Android Runtime Layer
Including the Core Libraries (<SDK Installation Dir>/android.jar) and Dalvik VM which is based upon Linux.
l Libraries Layer
Including Media Framework (general support for video, audio and image data), SQLite (lightweight “relational database” engine)
l Linux Kernel Layer
It is based on Linux 2.6.23 kernel,
Including drivers for all kinds of mobile platform components which need hardware support, such as GSM Telephony, Bluetooth/EDGE/3G/WiFi, Camera, GPS and etc.
2) Android is a complete OS, not just an API framework. Unlike the J2ME framework that is based on a certain native platform.
2. Android SDK & Eclipse IDE
1) Install JDK 5 or JDK 6.
2) Download Android SDK from http://code.google.com/android/download.html and unzip it to some folder without space in the path.
3) Download Eclipse IDE 3.3(Europa), 3.4(Ganymede) or higher version from:
http://www.eclipse.org/downloads/.
Somebody suggests downloading the “Eclipse IDE for Java EE Developers” version rather than “Eclipse IDE for Java Developers”. The latter version maybe lack of some tool to deploy and develop applications for server.
The Eclipse IDE should contain Ant 1.7 or upper version in order to build Android application.
4) Download and install the plug-ins for Eclipse IDE――ADT, refer to the document at:
http://code.google.com/android/intro/installing.html#installingplugin.
5) Add the path of JDK, ANT and Android SDK to the PATH system variable of your computer.
6) Command Line tools in Android SDK
i. Enter Android’s Linux Shell environment from WinXP
cd <Android Installation Folder>/tools
adb shell
adb kill-server (if you need restart the adb)
ii. Install Android application package
adb install d:/abc.apk
iii. Uninstall Android application package (3 options)
l adb shell rm abc.apk
l adb shell; (You MUST have the Emulator launched first)
#cd /data/app/;
#rm abc.apk
l adb uninstall <package name of abc.apk>
iv. Other command line tools:
l emulator -wipe-data: wipe your emulator data
l aidl
l aapt
l Profiler
l Resource building
l deployment
7) adb(Android debug bridge) tools in Android SDK
i. Runtime and debug tool in Android SDK, can work as simple Unix-like shell, the command format is:
adb shell [command]
l adb shell dmesg: print debug info of Linux
ii. File access:
l adb push: copy a file or folder to emulator
l adb pull: copy a file or folder from emulator
Sample: adb pull /data/data/kk.xml
l According to Richard, the file system is stored in the flash in the format of JFFS2.( http://twiki.mot.com/bin/view/IDEN/Android).
iii. Shutdown and restart adb tool
adb kill-server (if you need restart the adb)
8) Tips:
i. On Android SDK, no need to shot down and re-launch the emulator when code is changed. You can just rebuild and run the project, then the new binary file will be executed.
ii. If you delete classes of a project from hard disk directly, you need re-build the project. If you get some build errors, or the re-build process cannot proceed, you can try “Delete Project” from Eclipse IDE, “Import” the project again and then rebuild the project.
iii. Android does not give the SDK particular access to the phone’s file system, as Brew does. Nor does it offer a RecordStore, as does Java ME. Android provides lightweight SQLite database to access persistent data.
iv. Resource files’ name should not be initialized with digital. Because resource files’ name will be compiled into R.java as an int variable, which should not be initialized with digital.
v. Emulator Proxy Settings behind Motorola Firewall
http://twiki.mot.com/bin/view/IDEN/AndroidEmulatorProxySettings
9) More details please refer to webpage: http://code.google.com/android/intro/installing.html
3. External Resources
l Android Developers Google Group - Newsgroup for android developers. There is also an XML link so you can monitor topics/messages via RSS.
l Android Project Home - Documentations and starting guide for android developers and those who are interested.
l Android Developers - Android OS news, downloads, tutorials. We may get ideas from here about how to implement android API's, how our product will be like and what applications we may need.
l Opensource Android Projects on Google Code (currently 179 projects)
l Sample apps for Android - Open source sample apps
4. Android project directory structure
<Project Root>
</assets>
+ Similar to resources, but accessed via InputStream and read-only access.
</bin>
+ class files for source code
+ .apk file - Executable file on Android platform, it contain application's code and its resources, like .exe on Windows.
+ classes.dex file – Dalvik VM bytecode
+ resources.ap_ file – compiled binary resource file
</res>
<anim> -- XML files that are compiled into animation objects
<drawable> -- Image files (.jpg/.png/.bmp)
<layout> -- XML files that are compiled into screen layouts (or part of a screen).
<menu> -- XML files that are compiled into menu layouts
<raw> -- Arbitrary files to copy directly to the device, like sound files
<xml> -- Arbitrary XML files that are compiled and can be read at run time by calling Resources.getXML().
<values> -- XML files that can be compiled into many kinds of resource.
+ arrays.xml: define arrays
+ string.xml: ID and values for strings used in android
+ colors.xml: define color drawables and color string values.
+ dimens.xml: define dimension value.
+ styles.xml: define style objects.
+ <more...>
Using declarative XML file to determine the UI layout is one of most important differences from other platform. |
</src> -- source code of the Android application
+ R.java -- At compile time, Android generates a class named R that contains resource identifiers to all the resources in your program. The R class is an auto-generated file and is not designed to be edited by hand. It will be automatically re-created as needed when the resources are updated.
It seems a very strange design for building resource, which may have conflict with a user-defined R class.
Samples:
public static final class string {
}
public static final class layout {
};
public static final class drawable {
}
public static final class attr {
}
public static final class id {
}
5. Android application components
1) APK file -- Android application package
l Compile Java file to APK file
l .dex file
i. Dalvik VM executable
ii. More compressed form than byte-code
iii. 3rd party libraries can be converted to dex.
2) Task (aka. Application on other platform) -- There are four building blocks to an Android task/application:
l Activities
l Intents & Intent Receivers
l Services
l Content Providers
Ø Capable of spanning multiple processes
Ø Each task is associated with its own UI history stack, also known as the “visible activities stack??”
Ø Usually a task has an icon in the HOME screen, and it is available as a top-level item that can be brought to the foreground in front of other tasks.
3) Difference between APK, Task, Process, Thread
l A .apk is the file containing an application's code and its resources. This is the file that an application is distributed in and downloaded by the user when installing that application on their device.
l A task is generally what the user perceives as an "application" that can be launched: usually a task has an icon in the home screen through which it is accessed, and it is available as a top-level item that can be brought to the foreground in front of other tasks.
l A process is a low-level kernel process in which an application's code is running. Normally all of the code in a .apk is run in one, dedicated process for that .apk; however, the process tag can be used to modify where that code is run, either for the entire .apk or for individual activity, receiver, service, or provider, components.
In Android, processes are entirely an implementation detail of applications and NOT something the user is normally aware of.
l “APK” is a loose collection of components, including Activity/Intents/Services/Content Provider/Bundles etc. While “Task” is a bag of component instances that span processes and APKs.
4) Activities
l backbones of an application
l Typically corresponds to one screen in the UI
l Can save message or intermediate states into Bundles and recover the states with Bundles passed in. Bundle is similar to a simple Map, in the form of <name> : <value>.
5) Intents & Intent Receivers
l Communication officers between Activities, Services, content handlers, intent receivers and etc., one of the most important differences from other mobile platforms.
l Intent is description of what you want to do.
l Intent Receivers can (should) start Services for lengthy tasks (e.g. downloading new data)
l Intent Receivers need be registered in AndroidManifest.xml.
6) Services
l Can run in background process (process of the service own), or in the same process as Activity.
l Faceless, non-UI, run in background, e.g. music player, network download.
l Started by some other components explicitly or implicitly by binding the component to the service.
l Explicitly-started Services run until explicitly shut down (or killed by the system during a memory crunch). Implicitly-started Services run till the last client unbinds
7) Content Providers
l Enable data transmission/sharing with externals
l Work in “Façade” pattern, enable data sharing across applications and hide underlying implementation and work across processes.
6. Android Activity
1) General Description
l Android applications can have any number of activities registered with the handset through the AndroidManifest.xml file.
l Android’s multi-activity architecture is probably the major difference between developing for Android and developing for other handset SDKs, comparing with J2ME (extends MIDlet class) and BREW (define AEEClsCreateInstance function).
2) States path of an Activity
Figure - 1 States path of an Activity
3) States switch of an Activity
l Each Activity has its own Life Cycle
l Activity’s lifetime is not directly controlled by the Activity itself. Instead, it is determined by the system, considering how important this activity is to the user and how much overall memory is available in the system. The specific criteria need to be found out in later chapter.
Figure - 2 States switch of an Activity
4) Activity Lifetime & Visible Activities Stack
Figure - 3 Activities Lifecycle & Visible Activities Stack
5) Code sample of an Activity class
You do not need to use them all, but they are there.
public class Activity extends ApplicationContext {
protected void onCreate(Bundle savedInstanceState);
protected void onStart();
protected void onRestart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onDestroy();
protected void onFreeze();
}
Note: You should always call up to your super-class when implementing these methods. Especially the onCreate() method that will initialize the basic information of your Activity object.
6) Start a new activity or switch between activities.
Activiy.startActivity(Intent intent) | Synchronous call |
Activiy.startSubActivity() | Asynchronous, with handler callback (maybe obsolete) |
Activity.startActivityForResult(Intent, int requestCode) | Asynchronous, and your onActivityResult() method will be called back with the given requestCode, when the launched activity is finished. |
7. Android Process & Thread
1) General
i. Android process == Linux process (Android is also a Linux process??)
ii. System need kill processes to reclaim resources like memory.
iii. By default, 1 process per APK; By default, 1 thread per process
iv. Most components share one single thread, but Services and Content Providers sometimes can create new threads (but still in the same process).
2) Android process lifecycle
Process Types / States | Description | Importance |
Foreground Activity | The activity at the top of the screen that the user is currently interacting with | high |
Visible Activity | An activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog. |
|
Background Activity | An activity that is not visible to the user and has been paused. |
|
Empty process | Hosting no activities or other application components (such as Service or BroadcastReceiver classes). These are killed very quickly by the system as memory becomes low. | very low |
3) Zygote Process
A special process, need more information in Part II of this document.
4) Loopers in thread
<Inside the Android Application Framework.pdf> P27~30
8. Inter-Process Communication
1) In most cases, IPC is transparent to application’s code.
2) Specific APIs send data across process boundaries.
3) Generally two entry points
i. Bundles
a) Type-safe containers of C-like primitives, ints, strings, etc.
b) Simple data-passing APIs use Bundles
ii. Parcelables
4) AIDL -- Android Interface Definition Language
It is used for communication between Activity and other services, when Activity calling bindService( ). The communication includes data transferring, state query and etc.
If Activity just call startService() / stopService(), no need to use AIDL.
(Need more information.)
9. HelloWorld essentials
(Omitted).
10. Security and Permissions in Android
1) Security Architecture
An application's process is a secure sandbox. It cannot disrupt other applications, except by explicitly declaring the permissions it needs for additional capabilities those are not provided by the basic sandbox.
2) User ID & File Access
l Each Android package (.apk) file installed on the device is given its own “unique” Linux User ID, creating a sandbox for it and preventing it from touching other applications (or other applications from touching it). This user ID is assigned to it when the application is installed on the device, and remains constant for the duration of its life on that device.
Exception
Ø <init> process, Zygote and main runtime process
Ø By using the "sharedUserId" attribute in the AndroidManifest.xml's <manifest> tag, two APK files (only two) can run in the same process as the same application, with the same user ID and file permissions assigned.
l Any files created by an application will be assigned that application's user ID, and NOT normally accessible to other packages, except the application explicitly sets special tags to expose the files to outer world, or via explicitly-exposed APIs like Intents, services or Content Providers.
3) Permissions
l The check of “permissions” is at install time and the permission will not change after that (at runtime).
l You can NOT rely on “SecurityException is thrown” to aware a permission failure, for example when you broadcast something.
l Using Permission
Remember to use permission in AndroidManifest.xml, otherwise you will errors for some operations. Sample:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS /">
l Declaring and Enforcing Permission sample:
<permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"
android:label="@string/permlab_deadlyActivity"
android:description="@string/permdesc_deadlyActivity"
android:permissionGroup="android.permission-group.COST_MONEY"
android:protectionLevel="dangerous" />
l URI Permissions
Need more information.
l Process + User ID == security ???