Android 框架簡介

這篇文章寫的挺好的,適合有一定編程基礎的人學習Android,遂轉之!

 

======================= 第一節 ===========================

這裏簡單的介紹了Android的java環境基礎,在後面一節中會結合具體的實例來理解這一節的內容。

一、Dalvik虛擬機

Dalvik是Android的程序的java虛擬機,代碼在dalvik/下,

./
|-- Android.mk 
|-- CleanSpec.mk
|-- MODULE_LICENSE_APACHE2
|-- NOTICE



|-- README.txt 
|-- dalvikvm 虛擬機的實現庫   
|-- dexdump   
|-- dexlist 
|-- dexopt 
|-- docs 
|-- dvz 
|-- dx 
|-- hit 
|-- libcore 
|-- libcore-disabled 
|-- libdex 
|-- libnativehelper 使用JNI調用本地代碼時用到這個庫 
|-- run-core-tests.sh 
|-- tests 
|-- tools 
`-- vm

二、Android的java框架

Android層次中第3層是java框架,第四層就是java應用程序。

Android的java類代碼,主要是在frameworks/base/core/java/下,

./
|-- Android
|-- com
|-- jarjar-rules.txt
`-- overview.html

我們再看一下frameworks/base/目錄

./
|-- Android.mk
|-- CleanSpec.mk
|-- MODULE_LICENSE_APACHE2
|-- NOTICE
|-- api
|-- awt
|-- build
|-- camera
|-- cmds
|-- common
|-- core
|-- data
|-- docs
|-- graphics
|-- include
|-- keystore
|-- libs
|-- location
|-- media
|-- native
|-- obex
|-- opengl
|-- packages
|-- preloaded-classes
|-- sax
|-- services
|-- telephony
|-- test-runner
|-- tests
|-- tools
|-- vpn
`-- wifi

這裏也有Android的java框架代碼。

三、JNI

在Android中,通過JNI,java可以調用C寫的代碼,主要的實現是在frameworks/base/core/jni,通過查看Android.mk,我們可以看到最後生成了libandroid_runtime.so,具體實現JNI功能需要上面我們介紹的libnativehelper.so,

四、系統服務之java

1、binder,提供Android的IPC功能

2、servicemanager,服務管理的服務器端

3、系統進程zygote,負責孵化所有的新應用

======================= 第二節 ==========================

在我平時工作中主要是進行linux網絡子系統的模塊開發、linux應用程序(C/C++)開發。在學習和從事驅動模塊開發的過程中,如果你對linux系統本身,包括應用程序開發都不瞭解,那麼讀內核代碼就如同天書,毫無意義,所以我分析框架也是從基本系統api開始的,當然也不會太多涉及到應用程序開發。

好,開始這節主要是講一個簡單的adnroid應用程序,從應用程序出發,到框架代碼。


分析的應用程序我們也奉行拿來主義:froyo/development/samples/HelloActivity

./
|-- Android.mk
|-- AndroidManifest.xml
|-- res
|-- src
`-- tests

其他的就多說了,看代碼

[java] view plaincopy
  1. /*  
  2.  * Copyright (C) 2007 The Android Open Source Project  
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License");  
  5.  * you may not use this file except in compliance with the License.  
  6.  * You may obtain a copy of the License at  
  7.  *  
  8.  *      http://www.apache.org/licenses/LICENSE-2.0  
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS,  
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13.  * See the License for the specific language governing permissions and  
  14.  * limitations under the License.  
  15.  */    
  16. package com.example.Android.helloactivity;    
  17. import Android.app.Activity;    
  18. import Android.os.Bundle;    
  19. /**  
  20.  * A minimal "Hello, World!" application.  
  21.  */    
  22. public class HelloActivity extends Activity {    
  23.     public HelloActivity() {    
  24.     }    
  25.     /**  
  26.      * Called with the activity is first created.  
  27.      */    
  28.     @Override    
  29.     public void onCreate(Bundle savedInstanceState) {    
  30.         super.onCreate(savedInstanceState);    
  31.         // Set the layout for this activity.  You can find it     
  32.         // in res/layout/hello_activity.xml     
  33.         setContentView(R.layout.hello_activity);    
  34.     }    
  35. }     

每一個寫過Android程序的人都應該是從這個代碼起步的吧?那好,那麼我們研究android框架也從這裏啓航。

首先是

[java] view plaincopy
  1. import Android.app.Activity;    
  2. import Android.os.Bundle;    

記住,我們這裏不是講JAVA,我們要講的是Android.app.Activity,回顧上節的內容,android的JAVA框架代碼放在froyo/frameworks/base/,

其中Activity的代碼放在框架代碼的core/java/Android/app/Activity.java,大概看一下

[java] view plaincopy
  1. public class Activity extends ContextThemeWrapper    
  2.         implements LayoutInflater.Factory,    
  3.         Window.Callback, KeyEvent.Callback,    
  4.         OnCreateContextMenuListener, ComponentCallbacks {    
  5.     private static final String TAG = "Activity";    
  6.     /** Standard activity result: operation canceled. */    
  7.     public static final int RESULT_CANCELED    = 0;    
  8.     /** Standard activity result: operation succeeded. */    
  9.     public static final int RESULT_OK           = -1;    
  10.     /** Start of user-defined activity results. */    
  11.     public static final int RESULT_FIRST_USER   = 1;    
  12.     private static long sInstanceCount = 0;    

同樣的Bundle的代碼core/java/Android/os/Bundle.java

[java] view plaincopy
  1. public final class Bundle implements Parcelable, Cloneable {    
  2.     private static final String LOG_TAG = "Bundle";    
  3.     public static final Bundle EMPTY;    

呵呵,其實寫多應用程序,然後看看這些代碼,會有更加豁然開朗的感覺,所以列出以上目錄給大家參考,所有的java框架代碼都在那個目錄下,到這裏今天要討論的第一個問題就到這裏了。

我所在的公司是網絡設備供應商,其實和Android本身不搭邊,android只是平時的愛好而已,所以很多地方如果寫錯了敬請原諒,當然也計劃去做做android系統開發,例如驅動或者是框架開發,這是後話。

======================== 第三節 ========================

上節講到了JAVA框架代碼和應用程序的關係,那麼框架代碼和驅動層是怎麼聯繫的呢?這就是這一節的內容:JNI

java使用一種叫做jni的技術來支持對C/C++代碼的調用,在anroid中jni的代碼放在froyo/frameworks/base/core/jni下,當然在java框架代碼的目錄下還有其他地方也多多少少放了jni代碼,大家可以打開源碼來看看。

整體關係如下圖:


| java應用程序

--------------------------------------- Android系統api

| java框架

    |本地接口聲明

--------------------------------------

| JNI
--------------------------------------

| C/C++代碼

繼續拿來主義,C/C++中調試用printf,內核調試用printk,呵呵,Android調試用log,那麼我們就分析log的實現。

log的java代碼froyo/frameworks/base/core/java/Android/util/Log.java,

[java] view plaincopy
  1. /**  
  2.  * Copyright (C) 2006 The Android Open Source Project  
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License");  
  5.  * you may not use this file except in compliance with the License.  
  6.  * You may obtain a copy of the License at  
  7.  *  
  8.  *      http://www.apache.org/licenses/LICENSE-2.0  
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS,  
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13.  * See the License for the specific language governing permissions and  
  14.  * limitations under the License.  
  15.  */    
  16. package Android.util;    
  17. import com.Android.internal.os.RuntimeInit;    
  18. import java.io.PrintWriter;    
  19. import java.io.StringWriter;    
  20. /**  
  21.  * API for sending log output.  
  22.  *  
  23.  * <p>Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e()  
  24.  * methods.  
  25.  *  
  26.  * <p>The order in terms of verbosity, from least to most is  
  27.  * ERROR, WARN, INFO, DEBUG, VERBOSE.  Verbose should never be compiled  
  28.  * into an application except during development.  Debug logs are compiled  
  29.  * in but stripped at runtime.  Error, warning and info logs are always kept.  
  30.  *  
  31.  * <p><b>Tip:</b> A good convention is to declare a <code>TAG</code> constant  
  32.  * in your class:  
  33.  *  
  34.  * <pre>private static final String TAG = "MyActivity";</pre>  
  35.  *  
  36.  * and use that in subsequent calls to the log methods.  
  37.  * </p>  
  38.  *  
  39.  * <p><b>Tip:</b> Don't forget that when you make a call like  
  40.  * <pre>Log.v(TAG, "index=" + i);</pre>  
  41.  * that when you're building the string to pass into Log.d, the compiler uses a  
  42.  * StringBuilder and at least three allocations occur: the StringBuilder  
  43.  * itself, the buffer, and the String object.  Realistically, there is also  
  44.  * another buffer allocation and copy, and even more pressure on the gc.  
  45.  * That means that if your log message is filtered out, you might be doing  
  46.  * significant work and incurring significant overhead.  
  47.  */    
  48. public final class Log {    
  49.     /**  
  50.      * Priority constant for the println method; use Log.v.  
  51.      */    
  52.     public static final int VERBOSE = 2;    
  53.     /**  
  54.      * Priority constant for the println method; use Log.d.  
  55.      */    
  56.     public static final int DEBUG = 3;    
  57.     /**  
  58.      * Priority constant for the println method; use Log.i.  
  59.      */    
  60.     public static final int INFO = 4;    
  61.     /**  
  62.      * Priority constant for the println method; use Log.w.  
  63.      */    
  64.     public static final int WARN = 5;    
  65.     /**  
  66.      * Priority constant for the println method; use Log.e.  
  67.      */    
  68.     public static final int ERROR = 6;    
  69.     /**  
  70.      * Priority constant for the println method.  
  71.      */    
  72.     public static final int ASSERT = 7;    
  73.     /**  
  74.      * Exception class used to capture a stack trace in {@link #wtf()}.  
  75.      */    
  76.     private static class TerribleFailure extends Exception {    
  77.         TerribleFailure(String msg, Throwable cause) { super(msg, cause); }    
  78.     }    
  79.     private Log() {    
  80.     }    
  81.     /**  
  82.      * Send a {@link #VERBOSE} log message.  
  83.      * @param tag Used to identify the source of a log message.  It usually identifies  
  84.      *        the class or activity where the log call occurs.  
  85.      * @param msg The message you would like logged.  
  86.      */    
  87.     public static int v(String tag, String msg) {    
  88.         return println_native(LOG_ID_MAIN, VERBOSE, tag, msg);    
  89.     }    
  90.     /**  
  91.      * Send a {@link #VERBOSE} log message and log the exception.  
  92.      * @param tag Used to identify the source of a log message.  It usually identifies  
  93.      *        the class or activity where the log call occurs.  
  94.      * @param msg The message you would like logged.  
  95.      * @param tr An exception to log  
  96.      */    
  97.     public static int v(String tag, String msg, Throwable tr) {    
  98.         return println_native(LOG_ID_MAIN, VERBOSE, tag, msg + '/n' + getStackTraceString(tr));    
  99.     }    
  100.     /**  
  101.      * Send a {@link #DEBUG} log message.  
  102.      * @param tag Used to identify the source of a log message.  It usually identifies  
  103.      *        the class or activity where the log call occurs.  
  104.      * @param msg The message you would like logged.  
  105.      */    
  106.     public static int d(String tag, String msg) {    
  107.         return println_native(LOG_ID_MAIN, DEBUG, tag, msg);    
  108.     }    
  109.     /**  
  110.      * Send a {@link #DEBUG} log message and log the exception.  
  111.      * @param tag Used to identify the source of a log message.  It usually identifies  
  112.      *        the class or activity where the log call occurs.  
  113.      * @param msg The message you would like logged.  
  114.      * @param tr An exception to log  
  115.      */    
  116.     public static int d(String tag, String msg, Throwable tr) {    
  117.         return println_native(LOG_ID_MAIN, DEBUG, tag, msg + '/n' + getStackTraceString(tr));    
  118.     }    
  119.     /**  
  120.      * Send an {@link #INFO} log message.  
  121.      * @param tag Used to identify the source of a log message.  It usually identifies  
  122.      *        the class or activity where the log call occurs.  
  123.      * @param msg The message you would like logged.  
  124.      */    
  125.     public static int i(String tag, String msg) {    
  126.         return println_native(LOG_ID_MAIN, INFO, tag, msg);    
  127.     }    
  128.     /**  
  129.      * Send a {@link #INFO} log message and log the exception.  
  130.      * @param tag Used to identify the source of a log message.  It usually identifies  
  131.      *        the class or activity where the log call occurs.  
  132.      * @param msg The message you would like logged.  
  133.      * @param tr An exception to log  
  134.      */    
  135.     public static int i(String tag, String msg, Throwable tr) {    
  136.         return println_native(LOG_ID_MAIN, INFO, tag, msg + '/n' + getStackTraceString(tr));    
  137.     }    
  138.     /**  
  139.      * Send a {@link #WARN} log message.  
  140.      * @param tag Used to identify the source of a log message.  It usually identifies  
  141.      *        the class or activity where the log call occurs.  
  142.      * @param msg The message you would like logged.  
  143.      */    
  144.     public static int w(String tag, String msg) {    
  145.         return println_native(LOG_ID_MAIN, WARN, tag, msg);    
  146.     }    
  147.     /**  
  148.      * Send a {@link #WARN} log message and log the exception.  
  149.      * @param tag Used to identify the source of a log message.  It usually identifies  
  150.      *        the class or activity where the log call occurs.  
  151.      * @param msg The message you would like logged.  
  152.      * @param tr An exception to log  
  153.      */    
  154.     public static int w(String tag, String msg, Throwable tr) {    
  155.         return println_native(LOG_ID_MAIN, WARN, tag, msg + '/n' + getStackTraceString(tr));    
  156.     }    
  157.     /**  
  158.      * Checks to see whether or not a log for the specified tag is loggable at the specified level.  
  159.      *  
  160.      *  The default level of any tag is set to INFO. This means that any level above and including  
  161.      *  INFO will be logged. Before you make any calls to a logging method you should check to see  
  162.      *  if your tag should be logged. You can change the default level by setting a system property:  
  163.      *      'setprop log.tag.<YOUR_LOG_TAG> <LEVEL>'  
  164.      *  Where level is either VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT, or SUPPRESS. SUPPRESS will  
  165.      *  turn off all logging for your tag. You can also create a local.prop file that with the  
  166.      *  following in it:  
  167.      *      'log.tag.<YOUR_LOG_TAG>=<LEVEL>'  
  168.      *  and place that in /data/local.prop.  
  169.      *  
  170.      * @param tag The tag to check.  
  171.      * @param level The level to check.  
  172.      * @return Whether or not that this is allowed to be logged.  
  173.      * @throws IllegalArgumentException is thrown if the tag.length() > 23.  
  174.      */    
  175.     public static native boolean isLoggable(String tag, int level);    
  176.     /**  
  177.      * Send a {@link #WARN} log message and log the exception.  
  178.      * @param tag Used to identify the source of a log message.  It usually identifies  
  179.      *        the class or activity where the log call occurs.  
  180.      * @param tr An exception to log  
  181.      */    
  182.     public static int w(String tag, Throwable tr) {    
  183.         return println_native(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr));    
  184.     }    
  185.     /**  
  186.      * Send an {@link #ERROR} log message.  
  187.      * @param tag Used to identify the source of a log message.  It usually identifies  
  188.      *        the class or activity where the log call occurs.  
  189.      * @param msg The message you would like logged.  
  190.      */    
  191.     public static int e(String tag, String msg) {    
  192.         return println_native(LOG_ID_MAIN, ERROR, tag, msg);    
  193.     }    
  194.     /**  
  195.      * Send a {@link #ERROR} log message and log the exception.  
  196.      * @param tag Used to identify the source of a log message.  It usually identifies  
  197.      *        the class or activity where the log call occurs.  
  198.      * @param msg The message you would like logged.  
  199.      * @param tr An exception to log  
  200.      */    
  201.     public static int e(String tag, String msg, Throwable tr) {    
  202.         return println_native(LOG_ID_MAIN, ERROR, tag, msg + '/n' + getStackTraceString(tr));    
  203.     }    
  204.     /**  
  205.      * What a Terrible Failure: Report a condition that should never happen.  
  206.      * The error will always be logged at level ASSERT with the call stack.  
  207.      * Depending on system configuration, a report may be added to the  
  208.      * {@link Android.os.DropBoxManager} and/or the process may be terminated  
  209.      * immediately with an error dialog.  
  210.      * @param tag Used to identify the source of a log message.  
  211.      * @param msg The message you would like logged.  
  212.      */    
  213.     public static int wtf(String tag, String msg) {    
  214.         return wtf(tag, msg, null);    
  215.     }    
  216.     /**  
  217.      * What a Terrible Failure: Report an exception that should never happen.  
  218.      * Similar to {@link #wtf(String, String)}, with an exception to log.  
  219.      * @param tag Used to identify the source of a log message.  
  220.      * @param tr An exception to log.  
  221.      */    
  222.     public static int wtf(String tag, Throwable tr) {    
  223.         return wtf(tag, tr.getMessage(), tr);    
  224.     }    
  225.     /**  
  226.      * What a Terrible Failure: Report an exception that should never happen.  
  227.      * Similar to {@link #wtf(String, Throwable)}, with a message as well.  
  228.      * @param tag Used to identify the source of a log message.  
  229.      * @param msg The message you would like logged.  
  230.      * @param tr An exception to log.  May be null.  
  231.      */    
  232.     public static int wtf(String tag, String msg, Throwable tr) {    
  233.         tr = new TerribleFailure(msg, tr);    
  234.         int bytes = println_native(LOG_ID_MAIN, ASSERT, tag, getStackTraceString(tr));    
  235.         RuntimeInit.wtf(tag, tr);    
  236.         return bytes;    
  237.     }    
  238.     /**  
  239.      * Handy function to get a loggable stack trace from a Throwable  
  240.      * @param tr An exception to log  
  241.      */    
  242.     public static String getStackTraceString(Throwable tr) {    
  243.         if (tr == null) {    
  244.             return "";    
  245.         }    
  246.         StringWriter sw = new StringWriter();    
  247.         PrintWriter pw = new PrintWriter(sw);    
  248.         tr.printStackTrace(pw);    
  249.         return sw.toString();    
  250.     }    
  251.     /**  
  252.      * Low-level logging call.  
  253.      * @param priority The priority/type of this log message  
  254.      * @param tag Used to identify the source of a log message.  It usually identifies  
  255.      *        the class or activity where the log call occurs.  
  256.      * @param msg The message you would like logged.  
  257.      * @return The number of bytes written.  
  258.      */    
  259.     public static int println(int priority, String tag, String msg) {    
  260.         return println_native(LOG_ID_MAIN, priority, tag, msg);    
  261.     }    
  262.     /** @hide */ public static final int LOG_ID_MAIN = 0;    
  263.     /** @hide */ public static final int LOG_ID_RADIO = 1;    
  264.     /** @hide */ public static final int LOG_ID_EVENTS = 2;    
  265.     /** @hide */ public static final int LOG_ID_SYSTEM = 3;    
  266.     /** @hide */ public static native int println_native(int bufID,    
  267.             int priority, String tag, String msg);    
  268. }    

我們看到所有代碼都是調用public static native int println_native(int bufID,
            int priority, String tag, String msg);來實現輸出的,這個函數的實現就是C++,調用的方式就是JNI

我們看一下對應的jni代碼froyo/frameworks/base/core/jni/Android_util_Log.cpp,最終調用的輸出函數是

[java] view plaincopy
  1. /*  
  2.  * In class Android.util.Log:  
  3.  *  public static native int println_native(int buffer, int priority, String tag, String msg)  
  4.  */    
  5. static jint Android_util_Log_println_native(JNIEnv* env, jobject clazz,    
  6.         jint bufID, jint priority, jstring tagObj, jstring msgObj)    
  7. {    
  8.     const char* tag = NULL;    
  9.     const char* msg = NULL;    
  10.     if (msgObj == NULL) {    
  11.         jclass npeClazz;    
  12.         npeClazz = env->FindClass("java/lang/NullPointerException");    
  13.         assert(npeClazz != NULL);    
  14.         env->ThrowNew(npeClazz, "println needs a message");    
  15.         return -1;    
  16.     }    
  17.     if (bufID < 0 || bufID >= LOG_ID_MAX) {    
  18.         jclass npeClazz;    
  19.         npeClazz = env->FindClass("java/lang/NullPointerException");    
  20.         assert(npeClazz != NULL);    
  21.         env->ThrowNew(npeClazz, "bad bufID");    
  22.         return -1;    
  23.     }    
  24.     if (tagObj != NULL)    
  25.         tag = env->GetStringUTFChars(tagObj, NULL);    
  26.     msg = env->GetStringUTFChars(msgObj, NULL);    
  27.     int res = __Android_log_buf_write(bufID, (android_LogPriority)priority, tag, msg);    
  28.     if (tag != NULL)    
  29.         env->ReleaseStringUTFChars(tagObj, tag);    
  30.     env->ReleaseStringUTFChars(msgObj, msg);    
  31.     return res;    
  32. }    

當然我們發現最終輸出是

[java] view plaincopy
  1. int res = __Android_log_buf_write(bufID, (android_LogPriority)priority, tag, msg);    

用力grep了一下代碼,結果如下

[java] view plaincopy
  1. ./system/core/include/cutils/log.h:int __Android_log_buf_write(int bufID, int prio, const char *tag, const char *text);  
  2. ./system/core/liblog/logd_write.c:int __Android_log_buf_write(int bufID, int prio, const char *tag, const char *msg)  
  3. ./system/core/liblog/logd_write.c:    return __Android_log_buf_write(bufID, prio, tag, buf);  

這個就是和Android專用驅動進行通信的方式,這個分析下去就有點深了,後面分析。

以上三個小節分析了Android的JAVA環境,我這裏都是簡單的拋磚引玉,希望能給大家一點大體的指引,其他修行靠大家了,能成爲是一個android程序員是多麼幸福的事情,各位已經在幸福中了,我什麼時候也可以幸福一把??

發佈了1 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章