Android源码下载

来源:互联网 发布:阿里通信卡的网络2g 编辑:程序博客网 时间:2024/05/01 14:11

The Android source tree is located in a Git repository hosted by Google. The Git repository includes metadata for the Android source, including those related to changes to the source and the date they were made. This document describes how to download the source tree for a specific Android code-line.

Installing Repo


Repo is a tool that makes it easier to work with Git in the context of Android. For more information about Repo, see theDeveloping section.

To install Repo:

  1. Make sure you have a bin/ directory in your home directory and that it is included in your path:

    $ mkdir ~/bin$ PATH=~/bin:$PATH
  2. Download the Repo tool and ensure that it is executable:

    $ curl https://storage.googleapis.com/git-repo-downloads/repo > ~/bin/repo$ chmod a+x ~/bin/repo

For version 1.17, the SHA-1 checksum for repo is ddd79b6d5a7807e911b524cb223bc3544b661c28

For version 1.19, the SHA-1 checksum for repo is 92cbad8c880f697b58ed83e348d06619f8098e6c

For version 1.20, the SHA-1 checksum for repo is e197cb48ff4ddda4d11f23940d316e323b29671c

For version 1.21, the SHA-1 checksum for repo is b8bd1804f432ecf1bab730949c82b93b0fc5fede

For version 1.22, the SHA-1 checksum for repo is da0514e484f74648a890c0467d61ca415379f791

Initializing a Repo client


After installing Repo, set up your client to access the Android source repository:

  1. Create an empty directory to hold your working files. If you're using MacOS, this has to be on a case-sensitive filesystem. Give it any name you like:

    $ mkdir WORKING_DIRECTORY$ cd WORKING_DIRECTORY
  2. Configure git with your real name and email address. To use the Gerrit code-review tool, you will need an email address that is connected with aregistered Google account. Make sure this is a live address at which you can receive messages. The name that you provide here will show up in attributions for your code submissions.

    $ git config --global user.name "Your Name"$ git config --global user.email "you@example.com"
  3. Run repo init to bring down the latest version of Repo with all its most recent bug fixes. You must specify a URL for the manifest, which specifies where the various repositories included in the Android source will be placed within your working directory.

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

    To check out a branch other than "master", specify it with -b. For a list of branches, seeSource Code Tags and Builds.

    $ repo init -u https://android.googlesource.com/platform/manifest -b android-4.0.1_r1

A successful initialization will end with a message stating that Repo is initialized in your working directory. Your client directory should now contain a.repo directory where files such as the manifest will be kept.

Downloading the Android Source Tree


To pull down the Android source tree to your working directory from the repositories as specified in the default manifest, run

$ repo sync

The Android source files will be located in your working directory under their project names. The initial sync operation will take an hour or more to complete. For more aboutrepo sync and other Repo commands, see the Developing section.

Using Authentication


By default, access to the Android source code is anonymous. To protect the servers against excessive usage, each IP address is associated with a quota.

When sharing an IP address with other users (e.g. when accessing the source repositories from beyond a NAT firewall), the quotas can trigger even for regular usage patterns (e.g. if many users sync new clients from the same IP address within a short period).

In that case, it is possible to use authenticated access, which then uses a separate quota for each user, regardless of the IP address.

The first step is to create a password with the password generator and follow the instructions on the password generator page.

The second step is to force authenticated access, by using the following manifest URI:https://android.googlesource.com/a/platform/manifest. Notice how the/a/ directory prefix triggers mandatory authentication. You can convert an existing client to use mandatory authentication with the following command:

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

Troubleshooting network issues


When downloading from behind a proxy (which is common in some corporate environments), it might be necessary to explicitly specify the proxy that is then used by repo:

$ export HTTP_PROXY=http://<proxy_user_id>:<proxy_password>@<proxy_server>:<proxy_port>$ export HTTPS_PROXY=http://<proxy_user_id>:<proxy_password>@<proxy_server>:<proxy_port>

More rarely, Linux clients experience connectivity issues, getting stuck in the middle of downloads (typically during "Receiving objects"). It has been reported that tweaking the settings of the TCP/IP stack and using non-parallel commands can improve the situation. You need root access to modify the TCP setting:

$ sudo sysctl -w net.ipv4.tcp_window_scaling=0$ repo sync -j1

Using a local mirror


When using several clients, especially in situations where bandwidth is scarce, it is better to create a local mirror of the entire server content, and to sync clients from that mirror (which requires no network access). The download for a full mirror is smaller than the download of two clients, while containing more information.

These instructions assume that the mirror is created in /usr/local/aosp/mirror. The first step is to create and sync the mirror itself. Notice the--mirror flag, which can be specified only when creating a new client:

$ mkdir -p /usr/local/aosp/mirror$ cd /usr/local/aosp/mirror$ repo init -u https://android.googlesource.com/mirror/manifest --mirror$ repo sync

Once the mirror is synced, new clients can be created from it. Note that it's important to specify an absolute path:

$ mkdir -p /usr/local/aosp/master$ cd /usr/local/aosp/master$ repo init -u /usr/local/aosp/mirror/platform/manifest.git$ repo sync

Finally, to sync a client against the server, the mirror needs to be synced against the server, then the client against the mirror:

$ cd /usr/local/aosp/mirror$ repo sync$ cd /usr/local/aosp/master$ repo sync

It's possible to store the mirror on a LAN server and to access it over NFS, SSH or Git. It's also possible to store it on a removable drive and to pass that drive around between users or between machines.

Verifying Git Tags


Load the following public key into your GnuPG key database. The key is used to sign annotated tags that represent releases.

$ gpg --import

Copy and paste the key(s) below, then enter EOF (Ctrl-D) to end the input and process the keys.

-----BEGIN PGP PUBLIC KEY BLOCK-----Version: GnuPG v1.4.2.2 (GNU/Linux)mQGiBEnnWD4RBACt9/h4v9xnnGDou13y3dvOx6/t43LPPIxeJ8eX9WB+8LLuROSVlFhpHawsVAcFlmi7f7jdSRF+OvtZL9ShPKdLfwBJMNkU66/TZmPewS4m782ndtw78tR1cXb197Ob8kOfQB3A9yk2XZ4ei4ZC3i6wVdqHLRxABdncwu5hOF9KXwCgkxMDu4PVgChaAJzTYJ1EG+UYBIUEAJmfearb0qRAN7dEoff0FeXsEaUA6U90sEoVks0ZwNj96SA8BL+a1OoEUUfpMhiHyLuQSftxisJxTh+2QclzDviDyaTrkANjdYY7p2cq/HMdOY7LJlHaqtXmZxXjjtw5Uc2QG8UY8aziU3IE9nTjSwCXeJnuyvoizl9/I1S5jU5SA/9WwIps4SC84ielIXiGWEqq6i6/sk4I9q1YemZF2XVVKnmI1F4iCMtNKsR4MGSa1gA8s4iQbsKNWPgp7M3a51JCVCu6l/8zTpA+uUGapw4tWCp4o0dpIvDPBEa9b/aF/ygcR8mh5hgUfpF9IpXdknOsbKCvM9lSSfRciETykZc4wrRCVGhlIEFuZHJvaWQgT3BlbiBTb3VyY2UgUHJvamVjdCA8aW5pdGlhbC1jb250cmlidXRpb25AYW5kcm9pZC5jb20+iGAEExECACAFAknnWD4CGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRDorT+BmrEOeNr+AJ42Xy6tEW7r3KzrJxnRX8mij9z8tgCdFfQYiHpYngkI2t09Ed+9Bm4gmEO5Ag0ESedYRBAIAKVW1JcMBWvV/0Bo9WiByJ9WJ5swMN36/vAlQN4mWRhfzDOk/Rosdb0csAO/l8Kz0gKQPOfObtyYjvI8JMC3rmi+LIvSUT9806UphisyEmmHv6U8gUb/xHLIanXGxwhYzjgeuAXVCsv+EvoPIHbY4L/KvP5x+oCJIDbkC2b1TvVk9PryzmE4BPIQL/NtgR1oLWm/uWR9zRUFtBnE411aMAN3qnAHBBMZzKMXLWBGWE0znfRrnczI5p49i2YZJAjyX1P2WzmScK49CV82dzLo71MnrF6fj+Udtb5+OgTg7Cow+8PRaTkJEW5Y2JIZpnRUq0CYxAmHYX79EMKHDSThf/8AAwUIAJPWsB/MpK+KMs/s3r6nJrnYLTfdZhtmQXimpoDMJg1zxmL8UfNUKiQZ6esoAWtDgpqt7Y7sKZ8laHRARonte394hidZzM5nb6hQvpPjt2OlPRsyqVxw4c/KsjADtAuKW9/d8phbN8bTyOJo856qg4oOEzKG9eeF7oaZTYBy33BTL0408sEBxiMior6b8LrZrAhkqDjAvUXRwm/fFKgpsOysxC6xi553CxBUCH2omNV6Ka1LNMwzSp9ILz8jEGqmUtkBszwoG1S8fXgE0Lq3cdDM/GJ4QXP/p6LiwNF99faDMTV3+2SAOGvytOX6KjKVzKOSsfJQhN0DlsIw8hqJc0WISQQYEQIACQUCSedYRAIbDAAKCRDorT+BmrEOeCUOAJ9qmR0lEXzeoxcdoafxqf6gZlJZlACgkWF7wi2YLW3Oa+jv2QSTlrx4KLM==Wi5D-----END PGP PUBLIC KEY BLOCK-----

After importing the keys, you can verify any tag with

$ git tag -v TAG_NAME

If you haven't set up ccache yet, now would be a good time to do it.

转自:http://source.android.com/source/downloading.html#installing-repo



Accessory Development Kit 2012 Guide

The Android Accessory Development Kit (ADK) for 2012 is the latest reference implementation of anAndroid Open Accessory device,designed to help Android hardware accessory builders and software developers create accessoriesfor Android. The ADK 2012 is based on theArduino open sourceelectronics prototyping platform, with some hardware and software extensions that allow it tocommunicate with Android devices.

A limited number of these kits were produced and distributed at the Google I/O 2012 developerconference. If you did not receive one of these kits, fear not! The specifications and design filesfor the hardware were also released for use by manufacturers and hobbyists. You should expect to seekits with similar features available for purchase, or you can build one yourself!

One of the important new features demonstrated by this ADK is the ability to play audio over aUSB connection. Be sure to check out thereference implementation of a USBaudio dock in this ADK if you are interested in making audio-related USB accessories forAndroid.

Components


The ADK 2012 is based on the Arduino open source electronics prototyping platform and is an openhardware design. The hardware design files and firmware source code are included with the ADKsoftware download. The ADK contains two main physical hardware components:

  1. Main processing board containing the microprocessor, USB connections, power connector andinput/output pins. This board can be removed and used separately from the rest of the hardware.
  2. Shield containing sensors, LEDs, input controls, audio amplifier and speaker output, containedin a custom, polygon box enclosure.

The main hardware features of the ADK are as follows:

  • An ARM 32-bit Cortex M3 micro-processor
  • Separate USB connections for an Android device and computer connection for programming anddebugging
  • Sensors for light, color, proximity, temperature, humidity, barometric pressure, andacceleration
  • Micro SD Card slot
  • Bluetooth support

The ADK comes preloaded with an alarm clock firmware program that you can use immediately. Acompanion Android application,ADK 2012, isavailable on Google Play. The source code for both the Android application and the ADK firmware (anArduino sketch) can be downloaded from this page.

The ADK 2012 also comes with additional parts to help you develop accessories with it,including:

  • AC power adapter
  • USB A to Micro USB B connector cable
  • Micro USB B to Micro USB AB connector (small, rectangular plug)
  • Micro SD Card, preinstalled in the ADK SD Card socket

Using the Alarm Clock


An alarm clock program comes preloaded on the ADK. This firmware program allows you to use theADK as an alarm clock.

To use the ADK as an alarm clock:

  1. Open up the ADK by gently squeezing the two widest faces of the enclosure.
  2. Attach the provided AC power adapter (round connector) to the main ADK board, or attach a USBcable to the port markedComputer and a USB port on your computer.
  3. Place and hold your fingertip over the clock symbol on the control face.

    Note: You may need to hold your finger in place for 1-2seconds.

  4. Use the plus (+) and minus (-) symbols inside the clock digits to set the correct time.
  5. Place your fingertip over the alarm clock symbol to activate alarm setting.
  6. Use the plus (+) and minus (-) symbols inside the clock digits to set the alarm time.
  7. Use the plus (+) and minus (-) symbols inside the last two clock digits to turn the alarm on(on) or off (oF).
  8. To set the alarm tone, place and hold your fingertip over the alarm clock symbol, then tap theslider control on top of the enclosure.

To use the ADK 2012 companion application for the alarm clock:

  1. Load the companion application on your Android device running Android 3.1 (API Level 12) orhigher:
    • Using an NFC-enabled Android device, unlock and hold the device against the left side ofthe ADK enclosure. Follow the prompts to install the app.
      - or -
    • Start Google Play on your device, search for the ADK 2012 application andinstall it. If you cannot find the app, your device is not compatible. Try installing on anotherdevice.
  2. Connect your Android device to the ADK using one of the following methods:
    • To connect using Bluetooth:
      1. Plug the AC power adapter into the ADK.
      2. On your Android device, turn Bluetooth On (Settings >Bluetooth).
      3. In the Settings page, press the Bluetooth option toview paired devices.
      4. Select Search for Devices to locate the ADK 2012 accessory and followthe on screen instructions to connect.
      5. After pairing is complete, start the ADK 2012 app on your Androiddevice.
      6. On the start screen, select the Use Bluetooth button.
      7. In the list of paired devices, select the ADK 2012 device.
      8. The ADK 2012 app should switch to the menu screen and you can startinteracting with the ADK accessory.
    • To connect using USB:
      1. Plug the AC power adapter into the ADK.
      2. Connect the Micro USB AB connector (small, rectangular plug) to the port labeledPhone on the ADK board.
      3. Unlock your Android device and connect the Micro USB B connector to your device.

        Note: Your device must support Android USB accessorymode. Devices that support this mode include Google Nexus devices.

      4. On the Android device, you should see a prompt to connect to the ADK DemoKit2012, selectOK.
      5. The ADK 2012 app should start automatically and you can startinteracting with the ADK.

Note: When using the ADK with a USB connection to an Androiddevice, make sure the AC power adapter is plugged in. A USB connection to a computer does notprovide sufficient voltage to power both the ADK and a USB connection to a device.

Playing Audio


The ADK 2012 comes with audio output capabilities, including an amplifier and speaker. You canuse it to play audio from your Android device using either a Bluetooth or USB connection.

To play audio over Bluetooth:

  1. Follow the instructions in the previous section to connect your Androiddevice to the ADK over Bluetooth.
  2. On your Android device, navigate to the Settings > Bluetooth page to view thelist of paired devices, and make sure the ADK is connected.
  3. Select the settings icon next to the ADK 2012 item.
  4. Make sure the Media Audio option is enabled.
  5. Navigate to an application that plays music or other audio.
  6. Play a song or sound and listen to it on the ADK speaker!

To play audio over USB, you must use a device running Android 4.1 (API Level 16) or higher:

  1. Plug the AC power adapter into the ADK.
  2. Connect the Micro USB AB connector (small, rectangular plug) to the Phone port on the ADKboard.
  3. Unlock your Android device and connect the Micro USB B connector to your device.

    Note: Your device must support Android USB accessorymode. Devices that support this mode include Google Nexus devices.

  4. On the Android device, you should see a prompt to connect to the ADK DemoKit2012, selectCancel and allow the ADK to connect as a media deviceonly.
  5. Navigate to an application that plays music or other audio.
  6. Play a song or sound and listen to it on the ADK speaker!

Note: When using the ADK with a USB connection to an Androiddevice, make sure the AC power adapter is plugged in. A USB connection to a computer does notprovide sufficient voltage to power both the ADK and a USB connection to a device.

Developing Accessories with ADK 2012


The ADK 2012 is a hardware platform and a set of software libraries for prototyping Androidaccessories. This section discusses how to set up a development environment for programming the ADKto make it do what you want and to test software for building your own Android accessories.

Downloading the ADK Source

The support software and hardware specifications for the ADK 2012 are available from the Androidsource repository. Follow the instructions below to obtain the source material for the ADK.

To download the ADK 2012 software, source code and hardware design specifications.

  1. Download and install Git for your developmentsystem.
  2. Download and setup the repo tool, as described on the Android open sourceproject site.

    Note: Developers using Windows must use a Linux compatibilitypackage, such ascygwin, to install and run repo.Within your compatibility environment, you must install curl,git and python to be able to download and use the repo tool.

  3. In a terminal window, create a new directory for the downloaded source files, initialize andsynchronize a local repository:
    $> mkdir android-accessories$> cd android-accessories$> repo init -u https://android.googlesource.com/accessories/manifest$> repo sync

After successfully completing this process, you should have the source code and tools forworking with the ADK 2012:

  • adk2012/board - Source code and hardware design files for the ADK 2012
  • adk2012/app - Source code for the ADK 2012 Android companion application
  • external/ide - Source code for the ADK 2012 Integrated Development Environment(IDE)
  • external/toolchain - The toolchain used by the ADK 2012 IDE

Setting Up the Development Environment

The ADK 2012 comes with an integrated development environment (IDE) that you use to developsoftware and program the ADK 2012 accessory. The following instructions explain how to setup and runthe ADK 2012 IDE.

To set up and run the ADK 2012 IDE:

  1. Download and install the Java Development Kit 6 or higher from java.oracle.com.
  2. Download the ADK 2012 IDE for your development platform:
    • Windows
    • Mac
    • Linux 32bit, 64bit
  3. Unpack the downloaded archive.
  4. Run the application by navigating to the unpacked ADK2012_IDE/ folder and execute thearduino file.

After you have successfully installed and run the ADK 2012 IDE, you must configure it to usethe ADK 2012 library.

To configure the ADK 2012 IDE for use with the ADK libraries:

  1. Start the ADK 2012 IDE and choose File > Preferences.
  2. In the Preferences dialog, make a note of the Sketchbooklocation directory.
  3. Copy the <adk-source-download>/adk2012/board/library/ADK2 directory and itscontents into yoursketchbook/libraries/ directory, so that you create a sketchbook/libraries/ADK2 directory.
  4. Stop and restart the ADK 2012 IDE.
  5. In the IDE, choose File > Examples > ADK2 and then choose one of the examplesketches:
    • clock - The sketch that is preloaded onto the ADK 2012.
    • BluetoothScan - An example sketch demonstrating code that connects anaccessory to an Android device over Bluetooth.
    • usbaccessory - An example sketch demonstrating code that connects anaccessory to an Android device through a USB cable.
  6. Connect a Micro USB cable from the Computer port on the ADK board to yourdevelopment computer.
  7. In the ADK 2012 IDE, establish a serial port connection with the ADK byselectingTools > Serial Port and selecting the serial port for the ADK.
  8. In the ADK 2012 IDE, choose the ADK by selectingTools > Board >Google ADK2.
  9. Modify an example sketch or create your own.
  10. Upload the sketch to the ADK by choosing File > Upload. When theADK2012 IDE reports Done uploading, the sketch is uploaded and the ADK isready to communicate with your Android device.

Using the ADK Alternative Build System

An alternative, make file-based build and upload system is also available for the ADK 2012. Thissystem is command line based and intended for production environments where using an IDE environmentto load software onto accessory hardware may be inconvenient or undesirable.

To setup the environment:

  1. Download the ADK 2012 source code files.
  2. In a terminal window, navigate to <adk-source-download>/adk2012/board/MakefileBasedBuild.
  3. Execute the following command and follow the instructions:
    $> ./setup

To build a program for your accessory:

  1. Place your accessory code in the MakefileBasedBuild/app directory, including allrequired library files. See theapp/main.c file for an example of the program format.
  2. Execute the following command and follow the instructions:
    $> ./build

To load the program on your accessory hardware:

  1. Run the build process above and make sure your program compiled successfully.
  2. Attach the accessory via USB cable to your development computer.
  3. Check which port the accessory is attached to and modify the UART variable in theflash script to the correct port address. On linux machines, the port address is typically/dev/ttyUSB0.
  4. Execute the following command to load the program on the accessory:
    $> ./flash

How the ADK Connects with Android Devices


The essential feature of any Android accessory is its ability to connect and communicate with anAndroid device. Creating a fast and reliable connection between your accessory and Android devicesis the first order of business when building software for an accessory. This section describes theconnection and communication essentials used in the ADK 2012 so that you can apply them todeveloping your own Android accessories.

ADK Connection over Bluetooth

The ADK 2012 app and hardware accessory use a Bluetooth Serial Port Profile (SPP) connection tocommunicate. This connection allows two way communication between the ADK accessory and Androiddevices.

Note: The implementation of the ADK hardware allows the use ofother profiles and multiple connections. However, the basic communication between the ADK 2012accessory and the Android application uses SPP.

Accessory Bluetooth Code

In order to enable Bluetooth communications, the clock.ino sketch for the ADK 2012accessory calls abtStart() method during the setup() method to enable radiofrequency communications and start listening for Bluetooth connections:

ADK L;void setup() { L.adkInit(); L.btStart();}...void btStart(){    uint8_t i, dlci;    int f;    L.btEnable(adkBtConnectionRequest, adkBtLinkKeyRequest, adkBtLinkKeyCreated,               adkBtPinRequest, NULL);    dlci = L.btRfcommReserveDlci(RFCOMM_DLCI_NEED_EVEN);    if(!dlci) dbgPrintf("BTADK: failed to allocate DLCI\n");    else{        //change descriptor to be valid...        for(i = 0, f = -1; i < sizeof(sdpDescrADK); i++){            if(sdpDescrADK[i] == MAGIX){                if(f == -1) f = i;                else break;            }        }        if(i != sizeof(sdpDescrADK) || f == -1){            dbgPrintf("BTADK: failed to find a single marker in descriptor\n");            L.btRfcommReleaseDlci(dlci);            return;        }        sdpDescrADK[f] = dlci >> 1;        dbgPrintf("BTADK has DLCI %u\n", dlci);        L.btRfcommRegisterPort(dlci, btAdkPortOpen, btAdkPortClose, btAdkPortRx);        L.btSdpServiceDescriptorAdd(sdpDescrADK, sizeof(sdpDescrADK));    }}

Notice that the sdpDescrADK object contains a Universally Unique Identifier (UUID) in thevariableBT_ADK_UUID. This identifier must match the device UUID provided in theBluetoothSocket connection request in the Android application code.

Once Bluetooth is enabled with the code shown above, the accessory listens for connectionrequests. The ADK library handles listening and connection details, so the accessory callsADK::adkEventProcess() once during each loop execution:

void loop(void){  ...  L.adkEventProcess(); //let the adk framework do its thing  ...}

If a Bluetooth connection has been established, any commands are routed to thebtAdkPortRx() callback method (which was registered with the ADK library as part of thebtStart() method) and processed accordingly. The ADK accessory sends messages back throughthe Bluetooth connection using the ADK::btRfcommPortTx() method.For more details, review the implementations of these methods in theclock.ino sketch.

Android App Bluetooth Code

In the ADK 2012 Android app, the code for handling Bluetooth connections is encapsulated in in aBTConnection class. In this class, the application requests access to the Bluetooth adapterand negotiates a connection with the ADK 2012 accessory. Here is a summary of the relevant code:

mAdapter = BluetoothAdapter.getDefaultAdapter();BluetoothDevice device = mAdapter.getRemoteDevice(address);mSocket = device.createInsecureRfcommSocketToServiceRecord(ADK_UUID);mSocket.connect();

Note the ADK_UUID parameter in the second line. This identifier must match the identifieroutput by the accessory (theBT_ADK_UUID variable mentioned earlier), otherwise the protocolnegotiation fails and theBluetoothSocket is not created. Once aconnection is established, you obtainInputStream andOutputStreamobjects from the socket to communicate with the accessory:

mInStream = mSocket.getInputStream();mOutStream = mSocket.getOutputStream();

Review the BTConnection.java file provided in the ADK 2012 software download for moreimplementation details.

ADK Connection over USB

The ADK 2012 app and hardware accessory can also use a USB connection to communicate, similar tothe original ADK.

Accessory USB Code

The ADK library takes care of most of the implementation details for a USB connection, theaccessory code must make a few calls to initialize USB connectivity, including setting the accessoryidentification strings:

ADK L;void setup() {  L.adkInit();  L.usbSetAccessoryStringVendor(...);  L.usbSetAccessoryStringName(...);  L.usbSetAccessoryStringLongname(...);  L.usbSetAccessoryStringVersion(...);  L.usbSetAccessoryStringUrl(...);  L.usbSetAccessoryStringSerial(...);  L.usbStart();}

Note: The identification strings must match the USB accessoryfilter settings specified in the connecting Android application,otherwise the application cannotconnect with the accessory.

Once USB is enabled with code shown above, the accessory listens for connection requests. The ADKlibrary handles listening and connection details, so the accessory callsADK::adkEventProcess() once during each loop execution:

void loop(void){  ...  L.adkEventProcess(); //let the adk framework do its thing  ...}

The accessory must then check for a live USB connection to process commands and sendmessages. Here is a summary of the relevant code:

void loop() {  if (L.accessoryConnected()) {    int recvLen = L.accessoryReceive(msg, sizeof(msg));    if (recvLen > 0) {      ... // process message    }    L.accessorySend(outmsg, outmsgLen);  }  L.adkEventProcess();}

For more details, review the implementations of these methods in the clock.inosketch.

Android App USB Code

In the ADK 2012 Android app, the code for handling USB connections is encapsulated in aUsbConnection class. This class sets up aBroadcastReceiver tolisten for USB events and then attempts to connect when a matching connection event is received.Here is a summary of the relevant code:

import com.android.future.usb.UsbAccessory;import com.android.future.usb.UsbManager;mUSBManager = UsbManager.getInstance(this);UsbAccessory acc = mUSBManager.getAccessoryList()[0];if (!mUSBManager.hasPermission(acc)) return;

The ADK 2012 app uses the support library to implement the USB accessory connections, in order tosupport devices running Android 2.3.4 (API Level 10). If you only need to support Android3.1 (API Level 12) and higher devices, you can replace the first 4 lines the following code:

import android.hardware.usb.UsbAccessoryimport android.hardware.usb.UsbManagermUSBManager = (UsbManager) getSystemService(Context.USB_SERVICE);UsbAccessory acc = (UsbAccessory)                   intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);

Note that the app only receives events when the USB accessory identification information matchesthe information in theres/xml/usb_accessory_filter.xml file, referenced by theapplication’s manifest statement:

<meta-data    android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"    android:resource="@xml/usb_accessory_filter" />

Connections from other USB devices are not received by the ADK 2012 accessory.

Once the connection is established, the app can communicate with the accessory through file inputand output streams, as shown in the following example code:

ParcelFileDescriptor mFD = mUSBManager.openAccessory(acc);if (mFD != null) {  FileDescripter fd = mFD.getFileDescriptor();  mIS = new FileInputStream(fd);  // use this to receive messages  mOS = new FileOutputStream(fd); // use this to send commands}

Review the UsbConnection.java file provided in the ADK 2012 source code for moreimplementation details.

USB Audio Dock Implementation


One of the important new features introduced with the ADK 2012 is the ability to play audio overa USB connection. This innovation was introduced as an update to Android Open Accessory (AOA)protocol 2.0 and isavailable on devices running Android 4.1 (API Level 16) and higher.

The ADK 2012 provides a reference implementation of this functionality for accessory developers.No software application is required to be installed on the connected Android device, accessorydevelopers only need to support AOA v2. This implementation demonstrates audio output of 16bit,44.1kHz stereo PCM source data compressed into a single channel due to the audio hardware availableon the accessory.

Using the audio output features provided by the ADK library requires only a few function calls.The first few calls are in the accessorysetup() routine, which prepare the accessory forUSB connections and audio output, as summarized in the code example below:

ADK L;void setup() {  L.audioInit();  L.usbh_init()  L.usbStart();}

For more information about the ADK::audioInit() function, see thelibraries/ADK/Audio.c library file. For more information about the ADK::usbh_init()function, see the libraries/ADK/Usbh.c library file.

After completing this setup, the loop() function calls ADK::adkEventProcess() tohandle audio output and other ADK functions:

void loop(void){  ...  L.adkEventProcess(); //let the adk framework do its thing  ...}

This call executes task queuing for the ADK and as part of the execution process, the task queueexecutesusbh_work() in libraries/ADK/Usbh.c, which handles audio output requests.Review the implementation of this function for details. For additional implementation details onaudio output, see thelibraries/ADK/accessory.c library file.

转自:https://developer.android.com/adk/adk2.html#components


kernel下载

            内核的下载不需要repo这个工具,仅仅使用git的clone命令就可以了,不过一样面临地址被封需要绕过的问题。kernel代码大概600多M,比较小一点。
            $ git clone https://android.googlesource.com/kernel/common.git kernel
            命令行最后面的kernel的意思是保存在这个文件夹下,所以可以自行命名,系统会帮你创建出来的
            当然,还有其他的内核可以下载,从字面上看,msm应该是针对高通芯片的,omap是针对TI芯片的,samsung是针对三星芯片,tegra则是nVidia公司的芯片。
            $ git clone https://android.googlesource.com/kernel/goldfish.git
            $ git clone https://android.googlesource.com/kernel/msm.git
            $ git clone https://android.googlesource.com/kernel/omap.git
            $ git clone https://android.googlesource.com/kernel/samsung.git
            $ git clone https://android.googlesource.com/kernel/tegra.git


            下载完了之后可以用ls命令看一下,是不是kernel没看到任何代码?试着运行一下git的列出分支命令
            $ git branch -a,你会看到一系列分支,其中打*的分支是当前分支(刚下载完就是master啦),这个时候你切换一下分支,切换到你想要的分支代码就会出现了,我使用的是remotes/origin/android-2.6.39分支


            最后一点,如果需要代码和kernel同时下载,在./repo/manifests/default.xml文件中增加如下语句:

            <project path="kernel/common" name="kernel/common" revision="Android-2.6.39"/>

转自:http://blog.csdn.net/liuqz2009/article/details/51207384



0 0
原创粉丝点击