Android 框架简介

Android的java类代码,主要是在frameworks/base/core/java/下,如:Activity的代码放在框架代码的core/java/Android/app/Activity.java,

在Android中,通过JNI,java可以调用C写的代码,主要的实现是在frameworks/base/core/jni

adnroid示例应用程序:development/samples/



======================= 第一节 ===========================

这里简单的介绍了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

其他的就多说了,看代码

01/*
02 * Copyright (C) 2007 The Android Open Source Project
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 *      http://www.apache.org/licenses/LICENSE-2.0
09 *
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 */ 
16package com.example.Android.helloactivity; 
17import Android.app.Activity; 
18import Android.os.Bundle; 
19/**
20 * A minimal "Hello, World!" application.
21 */ 
22public class HelloActivity extends Activity { 
23    public HelloActivity() { 
24    
25    /**
26     * Called with the activity is first created.
27     */ 
28    @Override 
29    publicvoid 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框架也从这里启航。

首先是

1import Android.app.Activity; 
2import Android.os.Bundle;

记住,我们这里不是讲JAVA,我们要讲的是Android.app.Activity,回顾上节的内容,android的JAVA框架代码放在froyo/frameworks/base/,

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

01public classActivity extends ContextThemeWrapper 
02        implementsLayoutInflater.Factory, 
03        Window.Callback, KeyEvent.Callback, 
04        OnCreateContextMenuListener, ComponentCallbacks { 
05    privatestatic final String TAG = "Activity"
06    /** Standard activity result: operation canceled. */ 
07    publicstatic final int RESULT_CANCELED    = 0
08    /** Standard activity result: operation succeeded. */ 
09    publicstatic final int RESULT_OK           = -1
10    /** Start of user-defined activity results. */ 
11    publicstatic final int RESULT_FIRST_USER   = 1
12    privatestatic long sInstanceCount = 0;

同样的Bundle的代码core/java/Android/os/Bundle.java

1public finalclass Bundle implementsParcelable, Cloneable { 
2    privatestatic final String LOG_TAG = "Bundle"
3    publicstatic 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,

001/**
002 * Copyright (C) 2006 The Android Open Source Project
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */ 
016package Android.util; 
017import com.Android.internal.os.RuntimeInit; 
018import java.io.PrintWriter; 
019import java.io.StringWriter; 
020/**
021 * API for sending log output.
022 *
023 * <p>Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e()
024 * methods.
025 *
026 * <p>The order in terms of verbosity, from least to most is
027 * ERROR, WARN, INFO, DEBUG, VERBOSE.  Verbose should never be compiled
028 * into an application except during development.  Debug logs are compiled
029 * in but stripped at runtime.  Error, warning and info logs are always kept.
030 *
031 * <p><b>Tip:</b> A good convention is to declare a <code>TAG</code> constant
032 * in your class:
033 *
034 * <pre>private static final String TAG = "MyActivity";</pre>
035 *
036 * and use that in subsequent calls to the log methods.
037 * </p>
038 *
039 * <p><b>Tip:</b> Don't forget that when you make a call like
040 * <pre>Log.v(TAG, "index=" + i);</pre>
041 * that when you're building the string to pass into Log.d, the compiler uses a
042 * StringBuilder and at least three allocations occur: the StringBuilder
043 * itself, the buffer, and the String object.  Realistically, there is also
044 * another buffer allocation and copy, and even more pressure on the gc.
045 * That means that if your log message is filtered out, you might be doing
046 * significant work and incurring significant overhead.
047 */ 
048public finalclass Log { 
049    /**
050     * Priority constant for the println method; use Log.v.
051     */ 
052    publicstatic final int VERBOSE = 2
053    /**
054     * Priority constant for the println method; use Log.d.
055     */ 
056    publicstatic final int DEBUG = 3
057    /**
058     * Priority constant for the println method; use Log.i.
059     */ 
060    publicstatic final int INFO = 4
061    /**
062     * Priority constant for the println method; use Log.w.
063     */ 
064    publicstatic final int WARN = 5
065    /**
066     * Priority constant for the println method; use Log.e.
067     */ 
068    publicstatic final int ERROR = 6
069    /**
070     * Priority constant for the println method.
071     */ 
072    publicstatic final int ASSERT = 7
073    /**
074     * Exception class used to capture a stack trace in {@link #wtf()}.
075     */ 
076    privatestatic class TerribleFailure extends Exception { 
077        TerribleFailure(String msg, Throwable cause) {super(msg, cause); } 
078    
079    privateLog() { 
080    
081    /**
082     * Send a {@link #VERBOSE} log message.
083     * @param tag Used to identify the source of a log message.  It usually identifies
084     *        the class or activity where the log call occurs.
085     * @param msg The message you would like logged.
086     */ 
087    publicstatic int v(String tag, String msg) { 
088        returnprintln_native(LOG_ID_MAIN, VERBOSE, tag, msg); 
089    
090    /**
091     * Send a {@link #VERBOSE} log message and log the exception.
092     * @param tag Used to identify the source of a log message.  It usually identifies
093     *        the class or activity where the log call occurs.
094     * @param msg The message you would like logged.
095     * @param tr An exception to log
096     */ 
097    publicstatic int v(String tag, String msg, Throwable tr) { 
098        returnprintln_native(LOG_ID_MAIN, VERBOSE, tag, msg + '/n'+ getStackTraceString(tr)); 
099    
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    publicstatic int d(String tag, String msg) { 
107        returnprintln_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    publicstatic int d(String tag, String msg, Throwable tr) { 
117        returnprintln_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    publicstatic int i(String tag, String msg) { 
126        returnprintln_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    publicstatic int i(String tag, String msg, Throwable tr) { 
136        returnprintln_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    publicstatic int w(String tag, String msg) { 
145        returnprintln_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    publicstatic int w(String tag, String msg, Throwable tr) { 
155        returnprintln_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    publicstatic native boolean isLoggable(String tag, intlevel); 
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    publicstatic int w(String tag, Throwable tr) { 
183        returnprintln_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    publicstatic int e(String tag, String msg) { 
192        returnprintln_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    publicstatic int e(String tag, String msg, Throwable tr) { 
202        returnprintln_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    publicstatic int wtf(String tag, String msg) { 
214        returnwtf(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    publicstatic int wtf(String tag, Throwable tr) { 
223        returnwtf(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    publicstatic int wtf(String tag, String msg, Throwable tr) { 
233        tr = new TerribleFailure(msg, tr); 
234        intbytes = println_native(LOG_ID_MAIN, ASSERT, tag, getStackTraceString(tr)); 
235        RuntimeInit.wtf(tag, tr); 
236        returnbytes; 
237    
238    /**
239     * Handy function to get a loggable stack trace from a Throwable
240     * @param tr An exception to log
241     */ 
242    publicstatic 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        returnsw.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    publicstatic int println(int priority, String tag, String msg) { 
260        returnprintln_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(intbufID, 
267            intpriority, 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,最终调用的输出函数是

01/*
02 * In class Android.util.Log:
03 *  public static native int println_native(int buffer, int priority, String tag, String msg)
04 */ 
05static jint Android_util_Log_println_native(JNIEnv* env, jobject clazz, 
06        jint bufID, jint priority, jstring tagObj, jstring msgObj) 
07
08    constchar* tag = NULL; 
09    constchar* 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    intres = __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    returnres; 
32}

当然我们发现最终输出是

1int res = __Android_log_buf_write(bufID, (android_LogPriority)priority, tag, msg);

用力grep了一下代码,结果如下

1./system/core/include/cutils/log.h:int__Android_log_buf_write(intbufID, int prio, const char*tag, const char *text);
2./system/core/liblog/logd_write.c:int__Android_log_buf_write(intbufID, 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程序员是多么幸福的事情,各位已经在幸福中了,我什么时候也可以幸福一把??


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android框架是为了支持开发者轻松地构建Android应用程序而设计的一种软件框架。它由一系列库、API和工具组成,使开发者能够以更高效和更可靠的方式开发各种Android应用。 Android框架的核心组件是Android系统自带的四大组件:Activity、Service、BroadcastReceiver和ContentProvider。Activity负责应用程序的用户界面,Service负责后台运行的任务,BroadcastReceiver负责处理系统广播消息,ContentProvider负责管理应用程序的数据。 除了核心组件外,Android框架还提供了许多其他功能。其中之一是资源管理器,它允许开发者轻松访问应用程序的资源文件,如布局文件、图片和字符串。另一个重要功能是通知系统,它允许应用程序在状态栏上显示通知和提醒。 Android框架还提供了许多用于处理用户输入、网络通信、数据库访问等常见任务的类和接口。开发者可以使用这些工具来快速构建强大的Android应用程序。 值得一提的是,Android框架还允许开发者使用各种第三方库和工具来扩展功能。这些库和工具可以提供各种功能,如图形绘制、数据处理、网络通信等。开发者可以根据自己的需求选择适合的库和工具,以提高开发效率和应用程序的性能。 总的来说,Android框架是一个功能强大、灵活且易于使用的软件框架,它为开发者提供了丰富的工具和资源,使他们能够轻松构建高质量的Android应用程序。通过学习和掌握Android框架的各种组件和功能,开发者能够更好地利用Android平台的优势,为用户提供出色的移动应用体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值