顯示具有 Android Develop 標籤的文章。 顯示所有文章
顯示具有 Android Develop 標籤的文章。 顯示所有文章

2012年12月8日 星期六

[AOSP] Build Android Framework

Just brief note the steps to build AOSP

PC: i5-3210, 8G RAM, 750G HD
OS: Ubuntu 10.04 64 bits on VM WorkStation 8.0
Code Name: Jelly Bean
Tag: android-4.1.2_r1

Set up environment  ===========
1. Install Ubuntu 10.04 64 bits.
       http://releases.ubuntu.com/lucid/

2. Install Python.
$ sudo apt-get install python.
 
3. Install make
$ sudo apt-get update
$ sudo apt-get install gcc g++ build-essential
 
4. Install JDK6
$ sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk

 * If you got message below in step 4:
   Package sun-java6-jdk is not available, but is referred to by another package.
   This may mean that the package is missing, has been obsoleted, or
   is only available from another source
   E: Package 'sun-java6-jdk' has no installation candidate

 * Use following command instead
$ sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy multiverse"
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk

5. Install git
$ sudo apt-get install git-core

6. Install Required Package
$ sudo apt-get install git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc

7. Configuring USB Access
$ sudo gedit /etc/udev/rules.d/51-android.rules

 * Paste following text into the editing file and replace <username> to actual username

# adb protocol on passion (Nexus One)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e12", MODE="0600", OWNER="<username>"
# fastboot protocol on passion (Nexus One)
SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", ATTR{idProduct}=="0fff", MODE="0600", OWNER="<username>"
# adb protocol on crespo/crespo4g (Nexus S)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e22", MODE="0600", OWNER="<username>"
# fastboot protocol on crespo/crespo4g (Nexus S)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e20", MODE="0600", OWNER="<username>"
# adb protocol on stingray/wingray (Xoom)
SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", ATTR{idProduct}=="70a9", MODE="0600", OWNER="<username>"
# fastboot protocol on stingray/wingray (Xoom)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="708c", MODE="0600", OWNER="<username>"
# adb protocol on maguro/toro (Galaxy Nexus)
SUBSYSTEM=="usb", ATTR{idVendor}=="04e8", ATTR{idProduct}=="6860", MODE="0600", OWNER="<username>"
# fastboot protocol on maguro/toro (Galaxy Nexus)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e30", MODE="0600", OWNER="<username>"
# adb protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d101", MODE="0600", OWNER="<username>"
# fastboot protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d022", MODE="0600", OWNER="<username>"
# usbboot protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d00f", MODE="0600", OWNER="<username>"
# usbboot protocol on panda (PandaBoard ES)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d010", MODE="0600", OWNER="<username>"
# adb protocol on grouper (Nexus 7)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e42", MODE="0600", OWNER="<username>"
# fastboot protocol on grouper (Nexus 7)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e40", MODE="0600", OWNER="<username>"


  * After you save the file, execute following command.
    $ sudo chmod a+r /etc/udev/rules.d/51-android.rules

8. Setting up ccache
$ export USE_CCACHE=1


Download source  ============
1. Create a bin/ directory in home directory and make it included in path.
$ mkdir ~/bin
$ PATH=~/bin:$PATH

2. Download the Repo script
$ curl https://dl-ssl.google.com/dl/googlesource/git-repo/repo > ~/bin/repo
$ chmod a+x ~/bin/repo

3. Create a working directory, the name is up to you.
$ mkdir WORKING_DIRECTORY
$ cd WORKING_DIRECTORY

4. Run repo init
$ repo init -u https://android.googlesource.com/platform/manifest

5. Check out branch
$ repo init -u https://android.googlesource.com/platform/manifest -b android-4.1.2_r1

6. Start to download
$ repo sync

7. Verifying Git Tags, I don't know what the step for.
$ gpg --import

  * Paste following text, then enter Ctrl-D

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.2.2 (GNU/Linux)

mQGiBEnnWD4RBACt9/h4v9xnnGDou13y3dvOx6/t43LPPIxeJ8eX9WB+8LLuROSV
lFhpHawsVAcFlmi7f7jdSRF+OvtZL9ShPKdLfwBJMNkU66/TZmPewS4m782ndtw7
8tR1cXb197Ob8kOfQB3A9yk2XZ4ei4ZC3i6wVdqHLRxABdncwu5hOF9KXwCgkxMD
u4PVgChaAJzTYJ1EG+UYBIUEAJmfearb0qRAN7dEoff0FeXsEaUA6U90sEoVks0Z
wNj96SA8BL+a1OoEUUfpMhiHyLuQSftxisJxTh+2QclzDviDyaTrkANjdYY7p2cq
/HMdOY7LJlHaqtXmZxXjjtw5Uc2QG8UY8aziU3IE9nTjSwCXeJnuyvoizl9/I1S5
jU5SA/9WwIps4SC84ielIXiGWEqq6i6/sk4I9q1YemZF2XVVKnmI1F4iCMtNKsR4
MGSa1gA8s4iQbsKNWPgp7M3a51JCVCu6l/8zTpA+uUGapw4tWCp4o0dpIvDPBEa9
b/aF/ygcR8mh5hgUfpF9IpXdknOsbKCvM9lSSfRciETykZc4wrRCVGhlIEFuZHJv
aWQgT3BlbiBTb3VyY2UgUHJvamVjdCA8aW5pdGlhbC1jb250cmlidXRpb25AYW5k
cm9pZC5jb20+iGAEExECACAFAknnWD4CGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIX
gAAKCRDorT+BmrEOeNr+AJ42Xy6tEW7r3KzrJxnRX8mij9z8tgCdFfQYiHpYngkI
2t09Ed+9Bm4gmEO5Ag0ESedYRBAIAKVW1JcMBWvV/0Bo9WiByJ9WJ5swMN36/vAl
QN4mWRhfzDOk/Rosdb0csAO/l8Kz0gKQPOfObtyYjvI8JMC3rmi+LIvSUT9806Up
hisyEmmHv6U8gUb/xHLIanXGxwhYzjgeuAXVCsv+EvoPIHbY4L/KvP5x+oCJIDbk
C2b1TvVk9PryzmE4BPIQL/NtgR1oLWm/uWR9zRUFtBnE411aMAN3qnAHBBMZzKMX
LWBGWE0znfRrnczI5p49i2YZJAjyX1P2WzmScK49CV82dzLo71MnrF6fj+Udtb5+
OgTg7Cow+8PRaTkJEW5Y2JIZpnRUq0CYxAmHYX79EMKHDSThf/8AAwUIAJPWsB/M
pK+KMs/s3r6nJrnYLTfdZhtmQXimpoDMJg1zxmL8UfNUKiQZ6esoAWtDgpqt7Y7s
KZ8laHRARonte394hidZzM5nb6hQvpPjt2OlPRsyqVxw4c/KsjADtAuKW9/d8phb
N8bTyOJo856qg4oOEzKG9eeF7oaZTYBy33BTL0408sEBxiMior6b8LrZrAhkqDjA
vUXRwm/fFKgpsOysxC6xi553CxBUCH2omNV6Ka1LNMwzSp9ILz8jEGqmUtkBszwo
G1S8fXgE0Lq3cdDM/GJ4QXP/p6LiwNF99faDMTV3+2SAOGvytOX6KjKVzKOSsfJQ
hN0DlsIw8hqJc0WISQQYEQIACQUCSedYRAIbDAAKCRDorT+BmrEOeCUOAJ9qmR0l
EXzeoxcdoafxqf6gZlJZlACgkWF7wi2YLW3Oa+jv2QSTlrx4KLM=
=Wi5D
-----END PGP PUBLIC KEY BLOCK-----


Build   ===================
1. Set up environment
        $ . build/envsetup.sh

2. Choose a Target
        $ lunch full-eng

3. Build
        $ make -j4

The building process is done if you see message below.
Install system fs image: out/target/product/generic/system.img


Run on emulator  ===========
1. Boot up emulator.
        $ emulator


Reference:
http://source.android.com/source/index.html

[AOSP] make: *** [out/host/common/obj/JAVA_LIBRARIES/smali_intermediates/smaliLexer.java]

Problem:
When I built Android Frame android-4.1.2_r1 on Ubuntu, I got the error message below.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Vector.<init>(Vector.java:111)
at java.util.Vector.<init>(Vector.java:124)
at org.antlr.analysis.DFA.createTransitionTableEntryForState(DFA.java:551)
at org.antlr.analysis.DFA.createStateTables(DFA.java:440)
at org.antlr.codegen.CodeGenerator.genLookaheadDecision(CodeGenerator.java:645)
at org.antlr.grammar.v3.CodeGenTreeWalker.block(CodeGenTreeWalker.java:2876)
at org.antlr.grammar.v3.CodeGenTreeWalker.rule(CodeGenTreeWalker.java:2382)
at org.antlr.grammar.v3.CodeGenTreeWalker.rules(CodeGenTreeWalker.java:1537)
at org.antlr.grammar.v3.CodeGenTreeWalker.grammarSpec(CodeGenTreeWalker.java:1441)
at org.antlr.grammar.v3.CodeGenTreeWalker.grammar_(CodeGenTreeWalker.java:461)
at org.antlr.codegen.CodeGenerator.genRecognizer(CodeGenerator.java:421)
at org.antlr.Tool.generateRecognizer(Tool.java:655)
at org.antlr.Tool.process(Tool.java:468)
at org.antlr.Tool.main(Tool.java:93)
make: *** [out/host/common/obj/JAVA_LIBRARIES/smali_intermediates/smaliLexer.java] Error 1
make: *** Waiting for unfinished jobs....



Solution:
Open file in  
external/smali/smali/Android.mk
Find the line 
$(GEN): PRIVATE_CUSTOM_TOOL = java -jar $(ANTLR_JAR) -fo $(dir $@) $<
Change it to 
$(GEN): PRIVATE_CUSTOM_TOOL = java -Xmx512m -jar $(ANTLR_JAR) -fo $(dir $@) $<


Reference:
https://groups.google.com/forum/#!msg/android-building/Or1C6bpq8GQ/xAEMEEM0gKAJ


**********************************************************************
Related issues:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

at java.lang.String.toCharArray(String.java:2726)
at java.util.zip.ZipOutputStream.getUTF8Bytes(ZipOutputStream.java:483)
at java.util.zip.ZipOutputStream.writeLOC(ZipOutputStream.java:348)
at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:179)
at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:92)
at com.android.tools.layoutlib.create.AsmGenerator.createJar(AsmGenerator.java:241)
at com.android.tools.layoutlib.create.AsmGenerator.generate(AsmGenerator.java:225)
at com.android.tools.layoutlib.create.Main.main(Main.java:98)
make: *** [out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar] Error 1
make: *** Deleting file `out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar'

Edit the file
frameworks/base/tools/layoutlib/Android.mk

Reference:
https://groups.google.com/forum/?fromgroups=#!topic/android-building/D3QmmvsMRME


2012年9月4日 星期二

Necessitas Project

Necessitas is a KDE community project aimed to provide an easy way to develop Qt apps on Android platform.

Please see below link for detail.

http://necessitas.kde.org/
http://www.youtube.com/watch?v=suPeZ7XC1xk

2011年8月30日 星期二

[Android] How to read and parse xml files in android application.

I have a xml file named books.xml that is stored in my pad.

<?xml version="1.0" encoding="UTF-8"?>
<library-metadata title="My library">
  <book-metadata name="One Day" author="Nicholls, David">
    <publish-info publisher="Random House Inc" date="05-24-2011" ISBN="9780307946713"/>
  </book-metadata>
  <book-metadata name="Transformers: Exodus" author="Irvine, Alex">
    <publish-info publisher="Random House" date="06-28-2011" ISBN="9780345522528"/>
  </book-metadata>
</book-metadata>

I want to read the xml content and save it to my custom class.
The code as below.


        final String path = Environment.getExternalStorageDirectory().getPath() + "/books.xml";
        FileInputStream fstream = null;
        try
        {
            // read file.
            fstream = new FileInputStream(path);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(fstream);
            Element root = document.getDocumentElement();


            NodeList bookList = root.getElementsByTagName("book-metadata");
            for (int i = 0; i < bookList.getLength(); i++)
            {
                Element bookElement = (Element) bookList.item(i);


                NodeList publishList = bookElement.getElementsByTagName("publish-info");
                for (int j = 0; j < publishList.getLength(); j++)
                {
                    classBooks myBook = new classBooks();
                    Element publishElement = (Element) publishList.item(j);


                    // get xml value and set it into class object.
                    myBook.setName(Integer.parseInt(bookElement.getAttribute("name")));
                    myBook.setAuthor(bookElement.getAttribute("author"));
                    myBook.setPublisher(publishElement.getAttribute("publisher"));
                    myBook.setPublishDate(publishElement.getAttribute("date"));
                    myBook.setISBN(publishElement.getAttribute("ISBN"));


                    m_bookList.add(myBook);  // m_bookList is a member collection variable.
                }
            }
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
            if (null != fstream)
            {
                fstream.close();
            }
        }

2011年7月27日 星期三

[Android] Read string from external files

There is a txt file named text.txt and it's content as below.
hello string.

I put the file into sdcard of my Pad under folder named /myfile.
I want get the content of the file in my android program.

At first of all, making sure your sdcard is ready.

       File fileSDCard = null;
       if(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED))
       {
          return;
       }
       else
       {
           fileSDCard = Environment.getExternalStorageDirectory();
       }

next, open the file and read it.
       FileInputStream fstream = null;
       String readString = "";  
       try 
       {
           fstream = new FileInputStream(fileSDCard.getParent() + "/" + fileSDCard.getName() + "/myfile/test.txt");
           StringBuffer buffer = new StringBuffer();
           int readChar; 
           while ((readChar = fstream.read()) != -1) 
           { 
               buffer.append((char) readChar); 
           } 
           fstream.close(); 
           readString = buffer.toString(); 
       } 
       catch (Exception e) 
       {
           e.printStackTrace();
       }

It's done, so easy, isn't it?

2011年6月17日 星期五

[Android] Generating multitouch MotionEvents for testing

For testing the behaviour of the GestureDetector, i want to send MotionEvents to check action result.


Above android 2.3 we can use the method 'obtain' to get multitouch event.

public static MotionEvent obtain (long downTime, long eventTime, int action, int pointers, int[] pointerIds, PointerCoords[] pointerCoords, int metaState, float xPrecision, float yPrecision, int deviceId, int edgeFlags, int source, int flags)
            //action is an int variable indicate what event type to send. (DOWN, UP, POINIT_DOWN....)
            //point is an PointF array to indecate all coordinates touch on screen.
            int[] pointCoordsID = new int[point.length];
            PointerCoords[] pointCoords = new PointerCoords[point.length];
            for (int i = 0; i < point.length; i++) 
            {
                pointerIds[i] = i;
                pointerCoords[i] = new PointerCoords();
                pointerCoords[i].x = point[i].x;
                pointerCoords[i].y = point[i].y;
            }            
            long downTime = SystemClock.uptimeMillis();
            long eventTime = SystemClock.uptimeMillis();

            MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, point.lenth, pointCoordsID, pointCoords, 0, 1, 1, 0, 0, 0, 0);



#########################################################


If your device or sdk is android 2.2 or lower, you have to create MotionEvent from Parcel as below to perform it.


            //action is an int variable indicate what event type to send. (DOWN, UP, POINIT_DOWN....)
            //point is an PointF array to indecate all coordinates touch on screen.

            Parcel inParcel = Parcel.obtain();

            long downTime = SystemClock.uptimeMillis();
            long eventTime = SystemClock.uptimeMillis();
            inParcel.writeLong(downTime); //DownTime
            inParcel.writeLong(eventTime); //EventTime
            inParcel.writeInt(action);         //Action
            inParcel.writeInt(0);         //MetaState
            inParcel.writeFloat(point[0].x); //RawX
            inParcel.writeFloat(point[0].y); //RawY
            final int NP = m_point.length; //NumPointers
            inParcel.writeInt(NP);
            final int NS = m_point.length; //NumSamples
            inParcel.writeInt(NS);
            final int NI = NP*NS;
            if (NI > 0) 
            {
                int i;               
                //set point index
                for (i=0; i<NP; i++) 
                {
                inParcel.writeInt(i);
                }
                // set location, pressure, size for each sampleData
                int NUM_SAMPLE_DATA = 4;
                final int ND = NI*NUM_SAMPLE_DATA;
                float[] history = new float[ND];;
                for (i = 0; i < m_point.length; i++) 
                {
                history[i*NUM_SAMPLE_DATA] = point[i].x;
                history[i*NUM_SAMPLE_DATA + 1] = point[i].y;
                history[i*NUM_SAMPLE_DATA + 2] = 0;
                history[i*NUM_SAMPLE_DATA + 3] = 0;
                }
                for (i=0; i<ND; i++) 
                {
                inParcel.writeFloat(history[i]);
                }
                // set event time for each sampleData
                for (i=0; i<NS; i++) 
                {
                inParcel.writeLong(eventTime);
                }
            }
            inParcel.writeFloat(1); //PrecisionX
            inParcel.writeFloat(1); //PrecisionY
            inParcel.writeInt(0); //DeviceID
            inParcel.writeInt(0); //EdgeFlags
            
            inParcel.setDataPosition(0);
            
            MotionEvent event = MotionEvent.CREATOR.createFromParcel(inParcel);


###########################################


Reference:
http://stackoverflow.com/questions/3637044/generating-multitouch-motionevents-for-testing

2011年6月16日 星期四

[Android] Error: java.lang.NoClassDefFoundError

I got an error message: java.lang.NoClassDefFoundError

I tried to google antidote all day...

Here is a way to work it out but it doesn't match my case.
http://www.tech-recipes.com/rx/826/java-exception-in-thread-main-javalangnoclassdeffounderror/


Eventually, I found my SDK is android 3.0 but my device is android 2.2... (so stupid...)


Check SDK or device version is necessary.  :~|



2011年6月10日 星期五

[Android] Junit: get private variable, invoke private function

When we writing a JUnit test case, we sometimes need to get private member variable to verify the testing result or invoke private function to simulate software process.
We can use the object named PrivateAccessor to get private member like below.

To get private variable:
Integer.parseInt(PrivateAccessor.getPrivateField(Object, "Index").toString());

To invoke private function:
// The arguments to be passed to method
Object[] params = new Object[1]; 
params[0] = 0;
PrivateAccessor.invokePrivateMethod(Object, "functionName", params); 


Reference:
http://junit-addons.sourceforge.net/junitx/util/PrivateAccessor.html

2011年6月7日 星期二

[Android] Bound mismatch: The type XXX is not a valid substitute for the bounded parameter of the type ActivityInstrumentationTestCase2

I got an error message as title at android unit test case:
Bound mismatch: The type MyActivity is not a valid substitute for the bounded parameter <T extends Activity> of the type ActivityInstrumentationTestCase2<T>

I found the solution at link of reference and extract content as below:
The problem is that the android-support-v4.jar that you are using in your test project is different from the one in your application project. Remove all of the references to android-support-v4.jar from your test project. Then go to your application project Properties->Java Build Path->Order and Export and check android-support-v4.jar to export it. Now both projects will be using the same library, and dalvik won't complain.

Reference:
http://stackoverflow.com/questions/5561353/fragmentactivity-can-not-be-tested-via-activityinstrumentationtestcase2