2011-9-27 21:15:52

来源:互联网 发布:淘宝网店成本 编辑:程序博客网 时间:2024/04/26 17:08
 

2011-9-27 21:15:52

 


  首先在Android源代码工程中创建一个Android应用程序工程,名字就称为Process吧。
 
  关于如何获得Android源代码工程,请参考在Ubuntu上下载、编译和安装Android最新源代码一文;
 
  关于如何在Android源代码工程中创建应用程序工程,请参考在Ubuntu上为Android系统内置Java应用程序测试Application Frameworks层的硬件服务一文。
 
  这个应用程序工程定义了一个名为shy.luo.process的package,这个例子的源代码主要就是实现在这里了。下面,将会逐一介绍这个package里面的文件。

    应用程序的默认Activity定义在src/shy/luo/process/MainActivity.java文件中:


01.package shy.luo.process;      
02.     
03.import android.app.Activity;     
04.import android.content.Intent;     
05.import android.os.Bundle;     
06.import android.util.Log;     
07.import android.view.View;     
08.import android.view.View.OnClickListener;     
09.import android.widget.Button;     
10.     
11.public class MainActivity extends Activity  implements OnClickListener {     
12.    private final static String LOG_TAG = "shy.luo.process.MainActivity";     
13.     
14.    private Button startButton = null;     
15.     
16.    @Override     
17.    public void onCreate(Bundle savedInstanceState) {     
18.        super.onCreate(savedInstanceState);     
19.        setContentView(R.layout.main);     
20.     
21.        startButton = (Button)findViewById(R.id.button_start);     
22.        startButton.setOnClickListener(this);     
23.     
24.        Log.i(LOG_TAG, "Main Activity Created.");     
25.    }     
26.     
27.    @Override     
28.    public void onClick(View v) {     
29.        if(v.equals(startButton)) {     
30.            Intent intent = new Intent("shy.luo.process.subactivity");     
31.            startActivity(intent);     
32.        }     
33.    }     
34.}     
package shy.luo.process;    
   

package shy.luo.process;   
   
import android.app.Activity;   
import android.os.Bundle;   
import android.util.Log;   
import android.view.View;   
import android.view.View.OnClickListener;   
import android.widget.Button;   
   
public class SubActivity extends Activity implements OnClickListener {   
    private final static String LOG_TAG = "shy.luo.process.SubActivity";   
   
    private Button finishButton = null;   
   
    @Override   
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.sub);   
   
        finishButton = (Button)findViewById(R.id.button_finish);   
        finishButton.setOnClickListener(this);   
           
        Log.i(LOG_TAG, "Sub Activity Created.");   
    }   
   
    @Override   
    public void onClick(View v) {   
        if(v.equals(finishButton)) {   
            finish();   
        }   
    }   
}            它的实现也很简单,当点击上面的一个铵钮的时候,就结束自己,回到前面一个Activity中去。
        再来重点看一下应用程序的配置文件AndroidManifest.xml:

点击销毁

<?xml version="1.0" encoding="utf-8"?>   
<manifest xmlns:android="http://schemas.android.com/apk/res/android"   
    package="shy.luo.task"   
    android:versionCode="1"   
    android:versionName="1.0">   
    <application android:icon="@drawable/icon" android:label="@string/app_name">   
        <activity android:name=".MainActivity"   
                  android:label="@string/app_name"> 
                  android:process=":shy.luo.process.main" 
            <intent-filter>   
                <action android:name="android.intent.action.MAIN" />   
                <category android:name="android.intent.category.LAUNCHER" />   
            </intent-filter>   
        </activity>   
        <activity android:name=".SubActivity"   
                  android:label="@string/sub_activity" 
                  android:process=":shy.luo.process.sub">   
            <intent-filter>   
                <action android:name="shy.luo.task.subactivity"/>   
                <category android:name="android.intent.category.DEFAULT"/>   
            </intent-filter>   
        </activity>   
    </application>   
</manifest>         


为了使MainActivity和SubActivity在不同的进程中启动,我们分别配置了这两个Activity的android:process属性。

这样保证这2个不在同一个进程中。


The name of the process in which the activity should run. Normally, all components of an application run in the default process created for the application. It has the same name as the application package. The <application> element's process attribute can set a different default for all components. But each component can override the default, allowing you to spread your application across multiple processes.
        If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the activity runs in that process. If the process name begins with a lowercase character, the activity will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.

        大意为,一般情况下,同一个应用程序的Activity组件都是运行在同一个进程中,但是,如果Activity配置了android:process这个属性,那么,
       
        它就会运行在自己的进程中。如果android:process属性的值以":"开头,则表示这个进程是私有的;如果android:process属性的值以小写字母开头,则表示这是一个全局进程,
       
        允许其它应用程序组件也在这个进程中运行。

        因此,这里我们以":"开头,表示创建的是私有的进程。事实上,这里我们不要前面的":"也是可以的,但是必须保证这个属性性字符串内至少有一个"."字符,
       

全局 私有

 

public class PackageParser {

 ......

 private boolean parseApplication(Package owner, Resources res,
   XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
   throws XmlPullParserException, IOException {
  final ApplicationInfo ai = owner.applicationInfo;
  final String pkgName = owner.applicationInfo.packageName;

  TypedArray sa = res.obtainAttributes(attrs,
   com.android.internal.R.styleable.AndroidManifestApplication);

  ......

  if (outError[0] == null) {
   CharSequence pname;
   if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
    pname = sa.getNonConfigurationString(
     com.android.internal.R.styleable.AndroidManifestApplication_process, 0);
   } else {
    // Some older apps have been seen to use a resource reference
    // here that on older builds was ignored (with a warning).  We
    // need to continue to do this for them so they don't break.
    pname = sa.getNonResourceString(
     com.android.internal.R.styleable.AndroidManifestApplication_process);
   }
   ai.processName =
   
   
(ai.packageName, null, pname,
    flags, mSeparateProcesses, outError);

   ......
  }

  ......

 }

 private static String buildProcessName(String pkg, String defProc,
   CharSequence procSeq, int flags, String[] separateProcesses,
   String[] outError) {
  if ((flags&PARSE_IGNORE_PROCESSES) != 0 && !"system".equals(procSeq)) {
   return defProc != null ? defProc : pkg;
  }
  if (separateProcesses != null) {
   for (int i=separateProcesses.length-1; i>=0; i--) {
    String sp = separateProcesses[i];
    if (sp.equals(pkg) || sp.equals(defProc) || sp.equals(procSeq)) {
     return pkg;
    }
   }
  }
  if (procSeq == null || procSeq.length() <= 0) {
   return defProc;
  }
  return buildCompoundName(pkg, procSeq, "process", outError);
 }

 private static String buildCompoundName(String pkg,
   CharSequence procSeq, String type, String[] outError) {
  String proc = procSeq.toString();
  char c = proc.charAt(0);
  if (pkg != null && c == ':') {
   if (proc.length() < 2) {
    outError[0] = "Bad " + type + " name " + proc + " in package " + pkg
     + ": must be at least two characters";
    return null;
   }
   String subName = proc.substring(1);
   String nameError = validateName(subName, false);
   if (nameError != null) {
    outError[0] = "Invalid " + type + " name " + proc + " in package "
     + pkg + ": " + nameError;
    return null;
   }
   return (pkg + proc).intern();
  }
  String nameError = validateName(proc, true);
  if (nameError != null && !"system".equals(proc)) {
   outError[0] = "Invalid " + type + " name " + proc + " in package "
    + pkg + ": " + nameError;
   return null;
  }
  return proc.intern();
 }


 private static String validateName(String name, boolean requiresSeparator) {
  final int N = name.length();
  boolean hasSep = false;
  boolean front = true;
  for (int i=0; i<N; i++) {
   final char c = name.charAt(i);
   if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
    front = false;
    continue;
   }
   if (!front) {
    if ((c >= '0' && c <= '9') || c == '_') {
     continue;
    }
   }
   if (c == '.') {
    hasSep = true;
    front = true;
    continue;
   }
   return "bad character '" + c + "'";
  }

  return hasSep || !requiresSeparator
   ? null : "must have at least one '.' separator";
 }

 ......

}       

从调用parseApplication函数解析application标签开始,通过调用buildProcessName函数对android:process属性进解析,


接着又会调用buildCompoundName进一步解析,这里传进来的参数pkg就为"shy.luo.process",参数procSeq为MainActivity的属性android:process的值":shy.luo.process.main",


进一步将这个字符串保存在本地变量proc中。如果proc的第一个字符是":",则只需要调用validateName函数来验证proc字符串里面的字符都是合法组成就可以了,

即以大小写字母或者"."开头,后面可以跟数字或者"_"字符;如果proc的第一个字符不是":",除了保证proc字符里面的字符都是合法组成外,还要求至少有一个"."字符。

 
 MainActivity和SubActivity的android:process属性配置就介绍到这里了,其它更多的信息读者可以参考官方文档
 
 http://developer.android.com/guide/topics/manifest/activity-element.html或者源代码文件frameworks/base/core/java/android/content/pm/PackageParser.java。

        再来看界面配置文件,它们定义在res/layout目录中,main.xml文件对应MainActivity的界面: 

<?xml version="1.0" encoding="utf-8"?>   
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
    android:orientation="vertical"   
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent"    
    android:gravity="center">   
        <Button    
            android:id="@+id/button_start"   
            android:layout_width="wrap_content"   
            android:layout_height="wrap_content"   
            android:gravity="center"   
            android:text="@string/start" >   
        </Button>   
</LinearLayout>    

        而sub.xml对应SubActivity的界面:

<?xml version="1.0" encoding="utf-8"?>   
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
    android:orientation="vertical"   
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent"    
    android:gravity="center">   
        <Button    
            android:id="@+id/button_finish"   
            android:layout_width="wrap_content"   
            android:layout_height="wrap_content"   
            android:gravity="center"   
            android:text="@string/finish" >   
        </Button>   
</LinearLayout>         

 

<?xml version="1.0" encoding="utf-8"?>   
<resources>   
    <string name="app_name">Process</string>   
    <string name="sub_activity">Sub Activity</string>   
    <string name="start">Start activity in new process</string>   
    <string name="finish">Finish activity</string>   
</resources>        

  最后,我们还要在工程目录下放置一个编译脚本文件Android.mk:

 

LOCAL_PATH:= $(call my-dir)   
include $(CLEAR_VARS)   
   
LOCAL_MODULE_TAGS := optional   
   
LOCAL_SRC_FILES := $(call all-subdir-java-files)   
   
LOCAL_PACKAGE_NAME := Process   
   
include $(BUILD_PACKAGE)    


  接下来就要编译了。有关如何单独编译Android源代码工程的模块,以及如何打包system.img,请参考如何单独编译Android源代码中的模块一文。
       执行以下命令进行编译和打包:

view plaincopy to clipboardprint?
01.USER-NAME@MACHINE-NAME:~/Android$ mmm packages/experimental/Process       
02.USER-NAME@MACHINE-NAME:~/Android$ make snod    
USER-NAME@MACHINE-NAME:~/Android$ mmm packages/experimental/Process     
USER-NAME@MACHINE-NAME:~/Android$ make snod

         这样,打包好的Android系统镜像文件system.img就包含我们前面创建的Process应用程序了。
       再接下来,就是运行模拟器来运行我们的例子了。关于如何在Android源代码工程中运行模拟器,请参考在Ubuntu上下载、编译和安装Android最新源代码一文。
       执行以下命令启动模拟器:


在源码环境下进行编译