From d83a98f4ce9cfa908f5c54bbd70f03eec07e7553 Mon Sep 17 00:00:00 2001
From: The Android Open Source Project This document describes the default applications and settings that Google provides
- in their standard Android implementation. Android ships with Activities that handle the following Intent URI/Action pairs. Calls the entered phone number. Valid telephone numbers as defined
- in the IETF RFC 3966 are
- accepted. Valid examples include the following: The dialer is good at normalizing some kinds of schemes: for example
- telephone numbers, so the schema described isn't strictly required
- in the {@link android.net.Uri#parse(java.lang.String)
- Uri(URI string)} factory. However, if you have not tried a
- schema or are unsure whether it can be handled, use the {@link
- android.net.Uri#fromParts(java.lang.String, java.lang.String,
- java.lang.String) Uri.fromParts(scheme, ssp, fragment)} factory
- instead. Note: This requires your
- application to request the following permission in your manifest: tel:phone_number Dials (but does not actually initiate the call) the number given
- (or the stored voicemail on the phone). Telephone number normalization
- described for CALL applies to DIAL as well.
- The z field specifies the zoom level. A zoom level of 1 shows the whole Earth, centered at the
- given lat,lng. A zoom level of 2 shows a quarter of the Earth, and so on. The highest
- zoom level is 23. A larger zoom level will be clamped to 23.
-
- The cbll field is required. The cbp and mz fields are optional.
- The ApiDemos sample application includes many, many examples of common
-tasks and UI features. See the code inside
- Using the Android Eclipse plugin is the fastest and easiest way
-to start creating a new Android application. The plugin automatically generates
-the correct project structure for your application, and keeps the resources
-compiled for you automatically. It is still a good idea to know what is going on though. Take a look at Application Fundamentals
-to understand the basics of how an Android application works. You should also take a look at the ApiDemos application and the other sample
-applications included in the SDK, in the Finally, a great way to started with Android development in Eclipse is to
-follow both the Hello,
-World and Notepad code
-tutorials. In particular, the start of the Hello Android tutorial is an
-excellent introduction to creating a new Android application in Eclipse. This topic describes the manual steps in creating an Android application.
-Before reading this, you should read Application Fundamentals
-to understand the basics of how an Android application works. You might also
-want to look at the sample code included with the Android SDK, in the
- Here is a list of the basic steps in building an application.
-You can use a third party JAR in your application by adding it to your Eclipse project as follows:
-
-Alternatively, if you want to include third party JARs with your package, create a new directory for them within your project and select Add Library... instead.
-It is not necessary to put external JARs in the assets folder.
- Android calls a number of callbacks to let you draw your screen, store data before
- pausing, and refresh data after closing. You must implement at least some of
- these methods. See Lifecycles
- discussion in Application Fundamentals to learn when and in what order these methods
- are called. Here are some of the standard types of screen classes that Android provides: Your Activity will often need to open another Activity screen as it progresses.
- This new screen can be part of the same application or part of another application,
- the new screen can be floating or full screen, it can return a result, and you
- can decide whether to close this screen and remove it from the history stack
- when you are done with it, or to keep the screen open in history. These next
- sections describe all these options. When you open a new screen you can decide whether to make it transparent or floating,
- or full-screen. The choice of new screen affects the event sequence of events
- in the old screen (if the new screen obscures the old screen, a different
- series of events is called in the old screen). See Lifecycles discussion
- in Application Fundamentals for details. Transparent or floating windows are implemented in three
- standard ways: Calling startActivity() or startActivityForResult() will open a new screen in whatever
- way it defines itself (if it uses a floating theme it will be floating,
- otherwise it will be full screen). When you want to open a new screen, you can either explicitly specify the activity
- class to open, or you can let the operating system decide which screen to open,
- based upon the data and various parameters you pass in. A screen is opened by
- calling {@link android.app.Activity#startActivity(android.content.Intent) startActivity}
- and passing in an {@link android.content.Intent Intent} object, which specifies
- the criteria for the handling screen. To specify a specific screen, call Intent.setClass
- or setClassName with the exact activity class to open. Otherwise, set a variety
- of values and data, and let Android decide which screen is appropriate to open.
- Android will find one or zero Activities that match the specified requirements;
- it will never open multiple activities for a single request. More information
- on Intents and how Android resolves them to a specific class is given in the
- {@link android.content.Intent Intent} topic. The following snippet loads the com.android.samples.Animation1 class, and
- passes it some arbitrary data.: The next snippet requests that a Web page be opened by specifying the VIEW action,
- and a URI data string starting with "http://" schema: Here is the intent filter from the AndroidManifest.xml file for com.android.browser: Android defines a number of standard values, for instance the action constants
- defined by {@link android.content.Intent}. You can define custom values, but
- both the caller and handler must use them. See the <intent-filter>
- tag description in The AndroidManifest.xml
- File for more information on the manifest syntax for the handling
- application. A window can return a result after it closes. This result will be passed back
- into the calling Activity's {@link android.app.Activity#onActivityResult(int,int,android.content.Intent)
- onActivityResult()} method, which can supply an Intent containing arbitrary data, along with
- the request code passed to startActivityForResult(). Note that you must call the {@link
- android.app.Activity#startActivityForResult(android.content.Intent,int) startActivityForResult()}
- method that accepts a request code parameter to get this callback. The following
- code demonstrates opening a new screen and retrieving a result. An activity can remove itself from the history stack by calling {@link android.app.Activity#finish()
- Activity.finish()} on itself, or the activity that opened the screen can call
- {@link android.app.Activity#finishActivity(int) Activity.finishActivity()}
- on any screens that it opens to close them. Button click and other UI event capturing are covered in Handling UI Events on the UI Design page. You can set a number of general window properties, such as whether to display
- a title, whether the window is floating, and whether it displays an icon, by
- calling methods on the {@link android.view.Window Window} member
- of the underlying View object for the window. Examples include calling {@link
- android.app.Activity#getWindow() getWindow().requestFeature()} (or the convenience
- method {@link android.app.Activity#requestWindowFeature(int) requestWindowFeature(some_feature)})
- to hide the title. Here is an example of hiding the title bar:
-If you need to refer to your host computer's localhost, such as when you
-want the emulator client to contact a server running on the same host, use the alias
- If your application is dumped from memory because of space concerns, it will lose
- all user interface state information such as checkbox state and text box values
- as well as class member values. Android calls {@link android.app.Activity#onSaveInstanceState(android.os.Bundle)
- Activity.onSaveInstanceState} before it pauses the application. This method hands in a {@link
- android.os.Bundle Bundle} that can be used to store name/value pairs that will
- persist and be handed back to the application even if it is dropped from memory.
- Android will pass this Bundle back to you when it calls {@link android.app.Activity#onCreate(android.os.Bundle)
- onCreate()}. This Bundle only exists while the application is still in the history
- stack (whether or not it has been removed from memory) and will be lost when
- the application is finalized. See the topics for {@link android.app.Activity#onSaveInstanceState} and
- {@link android.app.Activity#onCreate} for
- examples of storing and retrieving state. Read more about the lifecycle of an application in Application Fundamentals. Your application can store files or complex collection objects, and reserve them
- for private use by itself or other activities in the application, or it can expose
- its data to all other applications on the device. See Storing,
- Retrieving, and Exposing Data to learn how to store and retrieve private data,
- how to store and retrieve common data from the device, and how to expose your
- private data to other applications. Please see the document Audio and Video for more details. You can create a listening class that can be notified or even instantiated whenever
- a specific type of system message is sent.
- The listening classes, called broadcast receivers, extend {@link android.content.BroadcastReceiver
- BroadcastReceiver}. If you want Android to instantiate the object whenever an appropriate
- intent notification is sent, define the receiver with a To send a notification, the caller creates an {@link android.content.Intent Intent}
- object and calls {@link android.app.Activity#sendBroadcast(android.content.Intent)
- Context.sendBroadcast()} with that Intent. Multiple recipients can receive
- the same message. You can broadcast an Intent message to an intent receiver in
- any application, not only your own. If the receiving class is not registered
- using Receivers can include intent filters to specify what kinds of intents they are
- listening for. Alternatively, if you expect a single known caller to contact
- a single known receiver, the receiver does not specify an intent filter, and
- the caller specifies the receiver's class name in the Intent by calling {@link
- android.content.Intent#setClassName(java.lang.String, java.lang.String) Intent.setClassName()}
- with the recipient's class name. The recipient receives a {@link android.content.Context
- Context} object that refers to its own package, not to the package of the sender. Note: If a receiver or broadcaster
- enforces permissions, your application might need to request permission
- to send or receive messages from that object. You can request permission by using
- the <uses-permission> tag in the manifest. Here is a code snippet of a sender and receiver. This example does not demonstrate
- registering receivers dynamically. For a full code example, see the AlarmService
- class in the ApiDemos project. Receiver AndroidManifest.xml (because there is no intent filter
- child, this class will only receive a broadcast when the receiver class is specified
- by name, as is done in this example): Receiver Java code: You can listen for other system messages sent by Android as well, such as USB
- connection/removal messages, SMS arrival messages, and timezone changes. See
- {@link android.content.Intent} for a list of broadcast messages to listen for.
- Messages are marked "Broadcast Action" in the documentation. The {@link android.telephony android.telephony} package overview page describes how to
- register to listen for phone events. Android provides an {@link android.app.AlarmManager AlarmManager} service that
- will let you specify an Intent to send at a designated time. This intent is typically
- used to start an application at a preset time. (Note: If you want to send
- a notification to a sleeping or running application, use {@link android.os.Handler
- Handler} instead.) There are two major kinds of alerts that you may display to the user:
-(1) Normal alerts are displayed in response to a user action, such as
-trying to perform an action that is not allowed. (2) Out-of-band alerts,
-called notifications, are
-displayed as a result of something happening in the background, such as the
-user receiving new e-mail. Android provides a number of ways for you to show popup notifications to your
- user as they interact with your application. {@link android.app.AlertDialog app.AlertDialog} This is a basic warning dialog box that lets you configure a message, button text,
- and callback. You can create one by calling using the {@link
- android.app.AlertDialog.Builder} class, as shown here. Out-of-band alerts should always be displayed using the
-{@link android.app.NotificationManager}, which allows you to tell the user
-about something they may be interested in without disrupting what they are
-currently doing. A notification can be anything from a brief pop-up box
-informing the user of the new information, through displaying a persistent
-icon in the status bar, to vibrating, playing sounds, or flashing lights to
-get the user's attention. In all cases, the user must explicitly shift their
-focus to the notification before they can interact with it. The following code demonstrates using NotificationManager to display a basic text
- popup when a new SMS message arrives in a listening service, and provides the
- current message count. You can see several more examples in the ApiDemos application,
- under app/ (named notification*.java).Intents handled by Google Android applications
-
-
-
diff --git a/docs/html/guide/appendix/faq/commontasks.jd b/docs/html/guide/appendix/faq/commontasks.jd
deleted file mode 100644
index 9c79bdd..0000000
--- a/docs/html/guide/appendix/faq/commontasks.jd
+++ /dev/null
@@ -1,812 +0,0 @@
-page.title=Common Tasks and How to Do Them in Android
-parent.title=FAQs, Tips, and How-to
-parent.link=index.html
-@jd:body
-
-
-
- Scheme
- Action
-
- android.intent.action.valueDescription
-
-
- http://web_address
-
- https://web_addressVIEW
- Open a browser window to the URL specified.
-
-
- "" (empty string)
-
- http://web_address
- https://web_addressWEB_SEARCH
- Opens the file at the location on the device in the browser.
-
-
- tel: phone_number
- CALL
-
-
-
- <uses-permission
- id="android.permission.CALL_PHONE" />
-
-
-
- voicemail:DIAL
-
-
-
- geo:latitude,longitude
-
- geo:latitude,longitude?z=zoom
- geo:0,0?q=my+street+address
- geo:0,0?q=business+near+city
- VIEW
- Opens the Maps application to the given location or query. The Geo URI scheme
- (not fully supported) is currently under
- development.
-
-
- google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom
-
- VIEW
- Opens the Street View application to the given location. The URI scheme is
- based on the syntax used for Street View panorama information in Google Maps URLs.
-
-
-
- Parameter Description
- lat latitude
- lng longitude
- yaw Panorama center-of-view in degrees clockwise from North.
- Note: The two commas after the yaw parameter are required. They are present
- for backwards-compatibility reasons.
- pitch Panorama center-of-view in degrees from
- -90 (look straight up) to 90 (look straight down.)
- zoom Panorama zoom. 1.0 = normal zoom, 2.0 = zoomed in 2x, 3.0 = zoomed in 4x, and so on.
- A zoom of 1.0 is 90 degree horizontal FOV for a nominal
- landscape mode 4 x 3 aspect ratio display.
- Android phones in portrait mode will adjust the zoom so that
- the vertical FOV is approximately the same as the landscape vertical
- FOV. This means that the horizontal FOV of an Android phone in portrait
- mode is much narrower than in landscape mode. This is done to minimize
- the fisheye lens effect that would be present if a 90 degree horizontal
- FOV was used in portrait mode.
- mapZoom The map zoom of the map location associated with this panorama. This value is passed on to the
- Maps activity when the Street View "Go to Maps" menu item is chosen. It corresponds to the z paramaeter in
- the geo: intent.
-
-<sdk>samples/ApiDemos and the other sample applications
-under the samples/ folder in the SDK.Creating an Android Application using the Eclipse Plugin
-
-<sdk>/samples/
-folder in the SDK.Creating an Android Application without the Eclipse Plugin
-
-<sdk>/samples/ directory.
-
-
-Adding an External Library (.jar) using Eclipse
-
-
-Implementing Activity Callbacks
-
-
-
-Opening a New Screen
-Floating or full?
-
-
-@android:style/Theme.Dialog
- in your AndroidManifest.xml file. For example:
-
-
-<activity class="AddRssItem" android:label="Add an item" android:theme="@android:style/Theme.Dialog"/>
-
-Opening a Screen
-Some Intent examples
-Intent myIntent = new Intent();
-myIntent.setClassName("com.android.samples", "com.android.samples.Animation1");
-myIntent.putExtra("com.android.samples.SpecialValue", "Hello, Joe!"); // key/value pair, where key needs current package prefix.
-startActivity(myIntent);
-Intent myIntent = new Intent(Intent.VIEW_ACTION, Uri.parse("http://www.google.com"));
-<intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <scheme android:name="http" />
- <scheme android:name="https" />
- <scheme android:name="file" />
-</intent-filter>
-Returning a Result from a Screen
-// Open the new screen.
-public void onClick(View v){
- // Start the activity whose result we want to retrieve. The
- // result will come back with request code GET_CODE.
- Intent intent = new Intent(this, com.example.app.ChooseYourBoxer.class);
- startActivityForResult(intent, CHOOSE_FIGHTER);
-}
-
-// Listen for results.
-protected void onActivityResult(int requestCode, int resultCode, Intent data){
- // See which child activity is calling us back.
- switch (resultCode) {
- case CHOOSE_FIGHTER:
- // This is the standard resultCode that is sent back if the
- // activity crashed or didn't doesn't supply an explicit result.
- if (resultCode == RESULT_CANCELED){
- myMessageboxFunction("Fight cancelled");
- }
- else {
- myFightFunction(data);
- }
- default:
- break;
- }
-}
-
-// Class SentResult
-// Temporary screen to let the user choose something.
- private OnClickListener mLincolnListener = new OnClickListener(){
- public void onClick(View v) {
- Bundle stats = new Bundle();
- stats.putString("height","6\'4\"");
- stats.putString("weight", "190 lbs");
- stats.putString("reach", "74\"");
- setResult(RESULT_OK, "Lincoln", stats);
- finish();
- }
- };
-
- private OnClickListener mWashingtonListener = new OnClickListener() {
- public void onClick(View v){
- Bundle stats = new Bundle();
- stats.putString("height","6\'2\"");
- stats.putString("weight", "190 lbs");
- stats.putString("reach", "73\"");
- setResult(RESULT_OK, "Washington", Bundle);
- finish();
- }
- };
-
-Lifetime of the new screen
-Listening for Button Clicks
-Configuring General Window Properties
-//Hide the title bar
-requestWindowFeature(Window.FEATURE_NO_TITLE);
-
-Referring to localhost from the emulated environment
-10.0.2.2 to refer to the host computer's loopback interface.
-From the emulator's perspective, localhost (127.0.0.1) refers to its own
-loopback interface.
-Storing and Retrieving State
-Storing and Retrieving Larger or More Complex Persistent Data
-Playing Media Files
-Listening For and Broadcasting Global Messages, and Setting Alarms
-<receiver> element
- in the AndroidManifext.xml file. If the caller is expected to instantiate the
- object in preparation to receive a message, this is not required. The receiver
- will get a call to their {@link android.content.BroadcastReceiver#onReceive(android.content.Context,android.content.Intent)
- BroadcastReceiver.onReceive()} method. A receiver can define an <intent-filter> tag
- that describes the types of messages it will receive. Just as Android's IntentResolver
- will look for appropriate Activity matches for a startActivity() call, it will
- look for any matching Receivers (but it will send the message to all matching
- receivers, not to the "best" match). <receiver> in its manifest, you can dynamically instantiate
- and register a receiver by calling {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter)
- Context.registerReceiver()}. Sending the message
-// We are sending this to a specific recipient, so we will
-// only specify the recipient class name.
-Intent intent = new Intent(this, AlarmReceiver.class);
-intent.putExtra("message","Wake up.");
-sendBroadcast(intent);
-
-Receiving the message
-
-<receiver class=".AlarmReceiver" />
-
-public class AlarmReceiver extends BroadcastReceiver{
- // Display an alert that we've received a message.
- @Override
- public void onReceive(Context context, Intent intent){
- // Send a text notification to the screen.
- NotificationManager nm = (NotificationManager)
- context.getSystemService(Context.NOTIFICATION_SERVICE);
- nm.notifyWithText(R.id.alarm,
- "Alarm!!!",
- NotificationManager.LENGTH_SHORT,
- null);
- }
-}
-Other system messages
-Listening for phone events
-Setting Alarms
-Displaying Alerts
-Normal Alerts
-
-
-
-
-
- Class
- Description
-
-
- {@link android.app.Dialog app.Dialog}
- A generic floating dialog box with a layout that you design.
-
-
-
- A popup alert dialog with two buttons (typically OK and Cancel) that
- take callback handlers. See the section after this table for more details.
-
-
- {@link android.app.ProgressDialog ProgressDialog}
- A dialog box used to indicate progress of an operation with a known progress
- value or an indeterminate length (setProgress(bool)). See Views > Progress Bar in
- ApiDemos for examples.
-
-
-Activity
- By setting the theme of an activity to
- {@link android.R.style#Theme_Dialog
- android:theme="android:style/Theme.Dialog"},
- your activity will take on
- the appearance of a normal dialog, floating on top of whatever was
- underneath it. You usually set the theme through the
- {@link android.R.attr#theme android:theme} attribute in your AndroidManifest.xml.
- The advantage of this
- over Dialog and AlertDialog is that Application has a much better managed
- life cycle than dialogs: if a dialog goes to the background and is killed,
- you cannot recapture state, whereas Application exposes a {@link android.os.Bundle
- Bundle} of saved values in
- onCreate() to help you maintain state.AlertDialog
-private Handler mHandler = new Handler() {
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case ACCEPT_CALL:
- answer(msg.obj);
- break;
-
- case BOUNCE_TO_VOICEMAIL:
- voicemail(msg.obj);
- break;
-
- }
- }
-};
-
-
-private void IncomingMotherInlawCall(Connection c) {
- String Text;
-
- // "Answer" callback.
- Message acceptMsg = Message.obtain();
- acceptMsg.target = mHandler;
- acceptMsg.what = ACCEPT_CALL;
- acceptMsg.obj = c.getCall();
-
- // "Cancel" callback.
- final Message rejectMsg = Message.obtain();
- rejectMsg.target = mHandler;
- rejectMsg.what = BOUNCE_TO_VOICEMAIL;
- rejectMsg.obj = c.getCall();
-
- new AlertDialog.Builder(this)
- .setMessage("Phyllis is calling")
- .setPositiveButton("Answer", acceptMsg)
- .setOnCanceListener(new OnCancelListener() {
- public void onCancel(DialogInterface dialog) {
- rejectMsg.sendToTarget();
- }});
- .show();
-}
-
-Notifications
-
-static void setNewMessageIndicator(Context context, int messageCount){
- // Get the static global NotificationManager object.
- NotificationManager nm = NotificationManager.getDefault();
To display a notification in the status bar and have it launch an intent when - the user selects it (such as the new text message notification does), call {@link - android.app.NotificationManager#notify(int, android.app.Notification) NotificationManager.notify()}, - and pass in vibration patterns, status bar icons, or Intents to associate with - the notification.
-An activity can display a progress bar to notify the user that something is happening. - To display a progress bar in a screen, call {@link android.app.Activity#requestWindowFeature(int) - Activity.requestWindowFeature(Window.FEATURE_PROGRESS)}. To set the value - of the progress bar, call {@link android.view.Window#setFeatureInt(int,int) - Activity.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level)}. - Progress bar values are from 0 to 9,999, or set the value to 10,000 to make the - progress bar invisible.
-You can also use the {@link android.app.ProgressDialog ProgressDialog} class, - which enables a dialog box with an embedded progress bar to send a "I'm working - on it" notification to the user.
-See Creating Menus.
- -Use the {@link android.webkit.WebView webkit.WebView} object.
-You can bind a ListView to a set of underlying data by using a shim class called - {@link android.widget.ListAdapter ListAdapter} (or a subclass). ListAdapter subclasses - bind to a variety of data sources, and expose a common set of methods such as - getItem() and getView(), and uses them to pick View items to display in its list. - You can extend ListAdapter and override getView() to create your own custom list - items. There are essentially only two steps you need to perform to bind to data:
-That's it!
-Here's an example of binding a ListActivity screen to the results from a cursor - query. (Note that the setListAdapter() method shown is a convenience method that - gets the page's ListView object and calls setAdapter() on it.)
-// Run a query and get a Cursor pointing to the results.
-Cursor c = People.query(this.getContentResolver(), null);
-startManagingCursor(c);
-
-// Create the ListAdapter. A SimpleCursorAdapter lets you specify two interesting things:
-// an XML template for your list item, and
-// The column to map to a specific item, by ID, in your template.
-ListAdapter adapter = new SimpleCursorAdapter(this,
- android.R.layout.simple_list_item_1, // Use a template that displays a text view
- c, // Give the cursor to the list adapter
- new String[] {People.NAME} , // Map the NAME column in the people database to...
- new String[] {"text1"}); // The "text1" view defined in the XML template
-setListAdapter(adapter);
-See view/List4 in the ApiDemos project for an example of extending ListAdapter - for a new data type.
- - - -You can get a handle to a screen element by calling {@link -android.app.Activity#findViewById(int) Activity.findViewById}. You can then use -the handle to set or retrieve any values exposed by the object.
-You can hook into the device's camera onto your own Canvas object by using the - {@link android.hardware.Camera Camera} class. See that class's documentation, - and the ApiDemos project's Camera Preview application (Graphics/Camera Preview) - for example code.
- - -Avoid performing long-running operations (such as network I/O) directly in the UI thread — -the main thread of an application where the UI is run — or your application may be blocked -and become unresponsive. Here is a brief summary of the recommended approach for handling expensive operations:
-The following outline illustrates a typical implementation:
- -
-public class MyActivity extends Activity {
-
- [ . . . ]
- // Need handler for callbacks to the UI thread
- final Handler mHandler = new Handler();
-
- // Create runnable for posting
- final Runnable mUpdateResults = new Runnable() {
- public void run() {
- updateResultsInUi();
- }
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- [ . . . ]
- }
-
- protected void startLongRunningOperation() {
-
- // Fire off a thread to do some work that we shouldn't do directly in the UI thread
- Thread t = new Thread() {
- public void run() {
- mResults = doSomethingExpensive();
- mHandler.post(mUpdateResults);
- }
- };
- t.start();
- }
-
- private void updateResultsInUi() {
-
- // Back in the UI thread -- update our UI elements based on the data in mResults
- [ . . . ]
- }
-}
-
-
-For further discussions on this topic, see -Designing for Responsiveness -and the {@link android.os.Handler} documentation.
- -You can highlight or style the formatting of strings or substrings of text in - a TextView object. There are two ways to do this:
-B (bold),
- I (italic), U (underline),
- TT (monospace), BIG, SMALL,
- SUP (superscript), SUB (subscript),
- and STRIKE (strikethrough).
- So, for example, in res/values/strings.xml you could declare this:<resource>
- <string>id="@+id/styled_welcome_message">We
- are <b><i>so</i></b> glad to see you.</string>
- </resources>To style text on the fly, you must make sure the TextView is using {@link android.text.Spannable} - storage for the text (this will always be true if the TextView is an EditText), - retrieve its text with {@link android.widget.TextView#getText}, and call {@link - android.text.Spannable#setSpan}, passing in a new style class from the {@link - android.text.style} package and the selection range.
-The following code snippet demonstrates creating a string with a highlighted section, - italic section, and bold section, and adding it to an EditText object.
-// Get our EditText object.
-EditText vw = (EditText)findViewById(R.id.text);
-
-// Set the EditText's text.
-vw.setText("Italic, highlighted, bold.");
-
-// If this were just a TextView, we could do:
-// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
-// to force it to use Spannable storage so styles can be attached.
-// Or we could specify that in the XML.
-
-// Get the EditText's internal text storage
-Spannable str = vw.getText();
-
-// Create our span sections, and assign a format to each.
-str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
-str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
-str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
-
-
--When using a search intent to ask the Maps activity to search for something, the Maps activity responds to the following attributes in the optional context bundle: -
-- float "centerLatitude" default 0.0f - float "centerLongitude" default 0.0f - float "latitudeSpan" default 0.0f - float "longitudeSpan" default 0.0f - int "zoomLevel" default 10 --
-This context information is used to center the search result in a particular area, and is equivalent to adjusting the Map activity to the described location and zoom level before issuing the query. -
--If the latitudeSpan, longitudeSpan, and zoomLevel attributes are not consistent, then it is undefined which one takes precedence. -
- -The following list describes the structure and files of an Android application. - Many of these files can be built for you (or stubbed out) by the activitycreator - application shipped in the tools/ menu of the SDK.
-| MyApp/ |
- - |
| AndroidManifest.xml | -(required) Advertises the screens that this application provides, - where they can be launched (from the main program menu or elsewhere), - any content providers it implements and what kind of data they handle, - where the implementation classes are, and other application-wide - information. Syntax details for this file are described in The AndroidManifest.xml File. | -
| src/ - /myPackagePath/.../MyClass.java |
- (required) This folder holds all the source code files for your - application, inside the appropriate package subfolders. | -
| res/ | -(required) This folder holds all the resources for - your application. Resources are external data files or description files - that are compiled into your code at build time. Files in different folders - are compiled differently, so you must put the proper resource into the - proper folder. (See Resources for details.) | -
| anim/ - animation1.xml - ... |
- (optional) Holds any animation XML description files that the - application uses. The format of these files is described in Resources. | -
| drawable/ - some_picture.png - some_stretchable.9.png - some_background.xml - ... |
- (optional) Zero or more files that will be compiled to {@link - android.graphics.drawable android.graphics.drawable} resources. Files - can be image files (png, gif, or other) or XML files describing other - graphics such as bitmaps, stretchable bitmaps, or gradients. Supported - bitmap file formats are PNG (preferred), JPG, and GIF (discouraged), - as well as the custom 9-patch stretchable bitmap format. These formats - are described in Resources. | -
| layout/ - screen_1_layout.xml - ... |
- (optional) Holds all the XML files describing screens or parts - of screens. Although you could create a screen in Java, defining them - in XML files is typically easier. A layout file is similar in concept - to an HTML file that describes the screen layout and components. See User Interface for more information about designing screens, and Available Resource Types for the syntax of these files. | -
| values/ - arrays - classes.xml - colors.xml - dimens.xml - strings.xml - styles.xml - values.xml |
- (optional) XML files describing additional resources - such as strings, colors, and styles. The naming, quantity, and number - of these files are not enforced--any XML file is compiled, but these - are the standard names given to these files. However, the syntax - of these files is prescribed by Android, and described in Resources. - |
-
| xml/ | -(optional) XML files that can be read at run time on the device. | -
| raw/ | -(optional) Any files to be copied directly to the device. | -
To write log messages from your application:
-android.util.Log.Log.v(), Log.d(), Log.i(),
- Log.w(), or Log.e() to log messages.
- (See the {@link android.util.Log} class.)Log.e(this.toString(), "error: " + err.toString())ddms in your Android SDK /tools path.Note: If you are running Eclipse and -encounter a warning about the VM debug port when opening DDMS, you can ignore it -if you're only interested in logs. However, if you want to further inspect and -control your processes from DDMS, then you should close Eclipse before launching DDMS so that -it may use the VM debugging port.
- - diff --git a/docs/html/guide/appendix/faq/framework.jd b/docs/html/guide/appendix/faq/framework.jd deleted file mode 100644 index 76a19c5..0000000 --- a/docs/html/guide/appendix/faq/framework.jd +++ /dev/null @@ -1,198 +0,0 @@ -page.title=Android Application Framework FAQ -parent.title=FAQs, Tips, and How-to -parent.link=index.html -@jd:body - -All Activities and Services in an application run in a single process by
-default. If needed, you can declare an android:process attribute
-in your manifest file, to explicitly place a component (Activity/Service) in
-another process.
By default, all of the application code in a single process runs -in the main UI thread. This is the same thread -that also handles UI events. The only exception is the code that handles -IPC calls coming in from other processes. The system maintains a -separate pool of transaction threads in each process to dispatch all -incoming IPC calls. The developer should create separate threads for any -long-running code, to avoid blocking the main UI thread.
- - - - - -It depends on the type of data that you want to share:
- -To share primitive data between Activities/Services in an -application, use Intent.putExtras(). For passing primitive data that -needs to persist use the - -Preferences storage mechanism.
- -For sharing complex non-persistent user-defined objects for short -duration, the following approaches are recommended: -
-The android.app.Application is a base class for those who need to -maintain global application state. It can be accessed via -getApplication() from any Activity or Service. It has a couple of -life-cycle methods and will be instantiated by Android automatically if -your register it in AndroidManifest.xml.
- -An alternate way to make data accessible across Activities/Services is to use public static -fields and/or methods. You can access these static fields from any other -class in your application. To share an object, the activity which creates your object sets a -static field to point to this object and any other activity that wants to use -this object just accesses this static field.
- -You can also use a HashMap of WeakReferences to Objects with Long -keys. When an activity wants to pass an object to another activity, it -simply puts the object in the map and sends the key (which is a unique -Long based on a counter or time stamp) to the recipient activity via -intent extras. The recipient activity retrieves the object using this -key.
- -There are advantages to using a static Singleton, such as you can -refer to them without casting getApplication() to an -application-specific class, or going to the trouble of hanging an -interface on all your Application subclasses so that your various -modules can refer to that interface instead.
-But, the life cycle of a static is not well under your control; so -to abide by the life-cycle model, the application class should initiate and -tear down these static objects in the onCreate() and onTerminate() methods -of the Application Class
- - -Even while an application appears to continue running, the system -may choose to kill its process and restart it later. If you have data -that you need to persist from one activity invocation to the next, you -need to represent that data as state that gets saved by an activity when -it is informed that it might go away.
- -For sharing complex persistent user-defined objects, the -following approaches are recommended: -
If the shared data needs to be retained across points where the application -process can be killed, then place that data in persistent storage like -Application Preferences, SQLite DB, Files or ContentProviders. Please refer to -the Data Storage -for further details on how to use these components.
- - - - - - -The general mechanism to start a new activity if its not running— -or to bring the activity stack to the front if is already running in the -background— is the to use the NEW_TASK_LAUNCH flag in the startActivity() -call.
- - - - - -The remote service can define a callback interface and register it with the -clients to callback into the clients. The -{@link android.os.RemoteCallbackList RemoteCallbackList} class provides methods to -register and unregister clients with the service, and send and receive -messages.
- -The sample code for remote service callbacks is given in ApiDemos/RemoteService
- - - - - -Please read the Designing for Responsiveness -document.
- - - - - - -Whenever a package is added, an intent with PACKAGE_ADDED action -is broadcast by the system. Similarly when a package is removed, an -intent with PACKAGE_REMOVED action is broadcast. To receive these -intents, you should write something like this: -
- <receiver android:name ="com.android.samples.app.PackageReceiver"> - <intent-filter> - <action android:name="android.intent.action.PACKAGE_ADDED"/> - <action android:name="android.intent.action.PACKAGE_REMOVED"/> - - <data android:scheme="package" /> - </intent-filter> - </receiver> --
The source code for the full Android stack is available from the Android Open Source Project site. - -
Other mirrored GPL and LGPL'd components are available at http://code.google.com/p/android/downloads/list.
Notices for other licenses can be found within the SDK.
- -One of the best explanations for the reasoning behind releasing code under Apache2 can be found in a ArsTechnica article by Ryan Paul.
diff --git a/docs/html/guide/appendix/faq/security.jd b/docs/html/guide/appendix/faq/security.jd deleted file mode 100644 index b0d832b..0000000 --- a/docs/html/guide/appendix/faq/security.jd +++ /dev/null @@ -1,156 +0,0 @@ -page.title=Android Security FAQ -parent.title=FAQs, Tips, and How-to -parent.link=index.html -@jd:body - -The security and privacy of our users' data is of primary importance to the -Android Open Source Project. We are dedicated to building and maintaining one -of the most secure mobile platforms available while still fulfilling our goal -of opening the mobile device space to innovation and competition.
- -The Android Platform provides a rich security model -that allows developers to request the capabilities, or access, needed by their -application and to define new capabilities that other applications can request. -The Android user can choose to grant or deny an application's request for -certain capabilities on the handset.
- -We have made great efforts to secure the Android platform, but it is -inevitable that security bugs will be found in any system of this complexity. -Therefore, the Android team works hard to find new bugs internally and responds -quickly and professionally to vulnerability reports from external researchers. -
- - -You can reach the Android security team at security@android.com. If you like, you -can protect your message using our PGP -key.
- -We appreciate researchers practicing responsible disclosure by emailing us -with a detailed summary of the issue and keeping the issue confidential while -users are at risk. In return, we will make sure to keep the researcher informed -of our progress in issuing a fix and will properly credit the reporter(s) when -we announce the patch. We will always move swiftly to mitigate or fix an -externally-reported flaw and will publicly announce the fix once patches are -available to users.
- - -An important part of sustainably securing a platform, such as, Android is -keeping the user and security community informed of bugs and fixes. We will -publicly announce security bugs when the fixes are available via postings to -the android-security-announce -group on Google Groups. You can subscribe to this group as you would a mailing -list and view the archives here.
- -For more general discussion of Android platform security, or how to use -security features in your Android application, please subscribe to android-security-discuss. -
- - -As an open platform, Android allows users to load software from any -developer onto a device. As with a home PC, the user must be -aware of who is providing the software they are downloading and must decide -whether they want to grant the application the capabilities it requests. -This decision can be informed by the user's judgment of the software -developer's trustworthiness, and where the software came from.
- -Despite the security protections in Android, it is important -for users to only download and install software from developers they trust. -More details on how Android users can make smart security decisions will be -released when consumer devices become available.
- - -Like any other open platform, it will be possible for unethical developers -to create malicious software, known as malware, for Android. If you -think somebody is trying to spread malware, please let us know at security@android.com. Please include as -much detail about the application as possible, with the location it is -being distributed from and why you suspect it of being malicious software.
- -The term malicious software is subjective, and we cannot make an -exhaustive definition. Some examples of what the Android Security Team believes -to be malicious software is any application that: -
The manufacturer of each device is responsible for distributing software -upgrades for it, including security fixes. Many devices will update themselves -automatically with software downloaded "over the air", while some devices -require the user to upgrade them manually.
- -When Android-powered devices are publicly available, this FAQ will provide links how -Open Handset Alliance members release updates.
- -Android is a mobile platform that will be released as open source and -available for free use by anybody. This means that there will be many -Android-based products available to consumers, and most of them will be created -without the knowledge or participation of the Android Open Source Project. Like -the maintainers of other open source projects, we cannot build and release -patches for the entire ecosystem of products using Android. Instead, we will -work diligently to find and fix flaws as quickly as possible and to distribute -those fixes to the manufacturers of the products.
- -In addition, We will add security fixes to the open source distribution of -Android and publicly announce the changes on android-security-announce. -
- -If you are making an Android-powered device and would like to know how you can -properly support your customers by keeping abreast of software updates, please -contact us at info@openhandsetalliance.com.
diff --git a/docs/html/guide/appendix/faq/troubleshooting.jd b/docs/html/guide/appendix/faq/troubleshooting.jd deleted file mode 100644 index 7c703e6..0000000 --- a/docs/html/guide/appendix/faq/troubleshooting.jd +++ /dev/null @@ -1,305 +0,0 @@ -page.title=Troubleshooting -parent.title=FAQs, Tips, and How-to -parent.link=index.html -@jd:body - - -Here are some tips and tricks for common Android errors. Don't forget to use the - ddms logcat capability to get a deeper view when errors occur. See Debugging for more debugging tips.
--The "Android Editors" feature of the ADT Plugin requires specific Eclipse components, such as WST. If you -encounter this error message during ADT installation, you need to install the -required Eclipse components and then try the ADT installation again. Follow the steps below to install the required components for the -Android Editors feature, based on the version of Eclipse that you are using.
- -| Eclipse 3.3 (Europa) | Eclipse 3.4 (Ganymede) |
|---|---|
-
|
-
-
|
-
Try restarting adb by stopping it (adb
- kill-server) then any other adb command to restart it.
<activity> tag for your app (or a <service> tag
- for a service, or a <receiver> tag for a receiver, etc.)? <action value="<something>">
- will often not be caught by compilers, but will prevent your application
- from being displayed because the intent filter will not be matched. Extra
- spaces or other characters can often sneak into these strings.adb logcat)
- and then install your .apk file. Check the logcat output to see whether the
- application is being installed and recognized properly. Here's sample output
- from a successful installation:
-I/FileObserver( 414): *** onEvent wfd: 3 mask: 8 path: MyRSSReader.apk -D/PackageManager( 414): Scanning package: /data/app/MyRSSReader.apk -D/PackageManager( 414): Adding package com.example.codelab.rssexample -D/PackageManager( 414): Registered content provider: my_rss_item, className = com.example.codelab.rssexample.RssContentProvider, isSyncable = false -D/PackageManager( 414): Providers: com.example.codelab.rssexample.RssContentProvider -D/PackageManager( 414): Activities: com.example.codelab.rssexample.MyRssReader com.example.codelab.rssexample.MyRssReader2-
Did you remember to send your .apk file to the device (adb - install)?
- -You might not have permission (or might not have requested permission) to - call this activity or receive this intent. Many standard Android activities, - such as making a call, have a permission assigned to it to prevent arbitrary - applications from sending or receiving requests. See Security and - Permissions for more information on permissions, and - {@link android.Manifest.permission Manifest.permission} for a list of - standard permissions supported by the Android platform. -
-If your project doesn't build, you may notice symptoms such as new
-resources added in the res/ sub-folders not showing up in the R class,
-the emulator not being started, not being able to run the application, or even seeming to run an old version of the application.
To troubleshoot these types of problems, first try:
-Window > Open Perspective > OtherReset ADB from the menu, and then try running the
- application againIf the above still doesn't work, you can try these steps:
-When communication doesn't seem to be happening between Eclipse and the emulator, symptoms can include: nothing happening when you press run, the emulator hanging waiting -for a debugger to connect, or errors that Eclipse reports about not being able -to find the emulator or shell. By far the most common symptom is that when you press run, the emulator starts (or -is already running), but the application doesn't start.
--You may find any of these steps will fix the problem and with practice you -probably can figure out which one you need to do for your particular issue, but -to start with, the safest option is to run through all of them in order:
-adb kill-server-
This error is displayed if you are using an older version of the JDK. Please make sure you are using JDK version 5 or 6.
- -The Android system requires that all applications be signed, as described in - Signing Your Applications. The ApiDemos -applications included with the SDK are preinstalled on the emulator and for that reason have been -compiled and signed with a private key.
- -If you want to modify or run one of the ApiDemos apps from Eclipse/ADT or other IDE, you can do so -so only after you uninstall the preinstalled version of the app from the emulator. If -you try to run an ApiDemos apps from your IDE without removing the preinstalled version first, -you will get errors similar to: - -[2008-08-13 15:14:15 - ApiDemos] Re-installation failed due to different application signatures. -[2008-08-13 15:14:15 - ApiDemos] You must perform a full uninstall of the application. WARNING: ...This will remove the application data! -[2008-08-13 15:14:15 - ApiDemos] Please execute 'adb uninstall com.android.samples' in a shell.- -
The error occurs because, in this case, you are attempting to install another copy of ApiDemos -onto the emulator, a copy that is signed with a different certificate (the Android IDE tools will -have signed the app with a debug certificate, where the existing version was already signed with -a private certificate). The system does not allow this type of reinstallation.
- -To resolve the issue, you need to fully uninstall the preinstalled and then reinstall it using -the adb tool. Here's how to do that:
- -emulator &.adb uninstall com.android.samples.adb install <path to the ApiDemos.apk>. If you are
- working in Eclipse/ADT, you can just compile and run the app in the normal way. Note that if multiple emulator instances are running, you need to direct your uninstall/install
-commands to the emulator instance that you are targeting. To do that you can add the
--s <serialNumber> to the command, for example:
adb -s emulator-5556 install- -
For more information about adb, see the Android Debug Bridge -documentation.
- - -If your development machine uses a locale that has a non-Gregorian calendar, you may encounter problems when first trying to compile and run your application. Specifically, you may find that the Android build tools won't compile your application because the debug key is expired.
- -The problem occurs because the Keytool utility — included in the JDK and used by the Android build tools — fails to properly handle non-Gregorian locales and may create validity dates that are in the past. That is, it may generate a debug key that is already expired, which results in the compile error.
- -If you encounter this problem, follow these steps to work around it:
- -debug.keystore file. On Linux/Mac OSX, the file is stored in ~/.android. On Windows XP, the file is stored in
-C:\Documents and Settings\<user>\Local Settings\Application Data\Android. On Windows Vista, the file is stored in
-C:\Users\<user>\AppData\Local\Androiddebug.keystore file from that computer to the proper location on your development machine. This problem has been verified on Windows and may apply to other platforms.
- -For general information about signing Android applications, see -Signing Your Applications.
- -If you are developing on Eclipse/ADT, you can add JUnit test classes to your application. However, you may get an error when trying to run such a class as a JUnit test:
- -Error occurred during initialization of VM -java/lang/NoClassDefFoundError: java/lang/ref/FinalReference- -
This error occurs because android.jar does not include complete Junit.* class implementations, but includes stub classes only.
- -To add a JUnit class, you have to set up a JUnit configuration:. - -
When configured in this way, your JUnit test class should now run properly.
- diff --git a/docs/html/guide/appendix/g-app-intents.jd b/docs/html/guide/appendix/g-app-intents.jd deleted file mode 100644 index d4f97c8..0000000 --- a/docs/html/guide/appendix/g-app-intents.jd +++ /dev/null @@ -1,112 +0,0 @@ -page.title=Intents List: Invoking Google Applications on Android Devices -@jd:body - -The table below lists the intents that your application can send, to invoke Google applications on Android devices in certain ways. For each action/uri pair, the table describes how the receiving Google application handles the intent.
- -Note that this list is not comprehensive.
- -| Target Application | -Intent URI | -Intent Action | -Result | -||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Browser | -http://web_address - https://web_address |
- VIEW | -Open a browser window to the URL specified. | -||||||||||||
| "" (empty string) - http://web_address - https://web_address |
- WEB_SEARCH | -Opens the file at the location on the device in the browser. | -|||||||||||||
| Dialer | -tel: phone_number | -CALL | -Calls the entered phone number. Valid telephone numbers as defined - in the IETF RFC 3966 are - accepted. Valid examples include the following: -
The dialer is good at normalizing some kinds of schemes: for example - telephone numbers, so the schema described isn't strictly required - in the {@link android.net.Uri#parse(java.lang.String) - Uri(URI string)} factory. However, if you have not tried a - schema or are unsure whether it can be handled, use the {@link - android.net.Uri#fromParts(java.lang.String, java.lang.String, - java.lang.String) Uri.fromParts(scheme, ssp, fragment)} factory - instead. -Note: This requires your
- application to request the following permission in your manifest: |
- ||||||||||||
tel:phone_number |
- DIAL | -Dials (but does not actually initiate the call) the number given - (or the stored voicemail on the phone). Telephone number normalization - described for CALL applies to DIAL as well. |
- |||||||||||||
| Google Maps | -geo:latitude,longitude - geo:latitude,longitude?z=zoom - geo:0,0?q=my+street+address - geo:0,0?q=business+near+city - |
- VIEW | -Opens the Maps application to the given location or query. The Geo URI scheme
- (not fully supported) is currently under
- development. - The z field specifies the zoom level. A zoom level of 1 shows the whole Earth, centered at the - given lat,lng. A zoom level of 2 shows a quarter of the Earth, and so on. The highest - zoom level is 23. A larger zoom level will be clamped to 23. - |
- ||||||||||||
| Google Streetview | -google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom - | -VIEW | -Opens the Street View application to the given location. The URI scheme is
- based on the syntax used for Street View panorama information in Google Maps URLs. - The cbll field is required. The cbp and mz fields are optional. -
|
-
The list below defines some of the basic terminology of the Android platform.
-.apk extension. For example:
- myExampleAppname.apk. For convenience, an application package
- file is often referred to as an ".apk".
- Related: Application.
-Android programs are compiled into .dex (Dalvik Executable) files, which - are in turn zipped into a single .apk file on the device. .dex files can - be created by automatically translating compiled applications written in - the Java programming language.
Related: Intent.
-Related: Drawable, OpenGL - ES.
Related: URI Usage in Android
Related: Activity.
Related: Intent Filter, Broadcast Receiver.
Related: Intent, Broadcast Receiver.
Related: Intent, Intent - Filter.
Related: Resources
Related: Resources.
res/* subfolders of the project. Related: Activity
Related: Canvas
Related: Surface
content://. In an Intent, a URI using an http://
- scheme will be handled by the browser. Related: View
The Core Media Formats table below describes the media format support built into the Android platform. Note that any given mobile device may provide support for additional formats or file types not listed here.
-For your convenience, the table T-Mobile G1 Media Formats describes the additional media formats supported by the T-Mobile G1 device.
- - -| Type | -Format | -Encoder | -Decoder | -Details | -File Type(s) Supported | -
|---|---|---|---|---|---|
| Audio | -AAC LC/LTP | -- | X | -Mono/Stereo content in any combination of standard bit rates up to 160 kbps and sampling rates from 8 to 48kHz | -3GPP (.3gp) and MPEG-4 (.mp4, .m4a). No support for raw AAC (.aac) | -
| HE-AACv1 (AAC+) | -- | X | -|||
| HE-AACv2 (enhanced AAC+) | -- | X | -|||
| AMR-NB | -X | -X | -4.75 to 12.2 kbps sampled @ 8kHz | -3GPP (.3gp) - | -|
| AMR-WB | -- | X | -9 rates from 6.60 kbit/s to 23.85 kbit/s sampled @ 16kHz | -3GPP (.3gp) | -|
| MP3 | -- | X | -Mono/Stereo 8-320Kbps constant (CBR) or variable bit-rate (VBR) - | -MP3 (.mp3) | -|
| MIDI | -- | X | -MIDI Type 0 and 1. DLS Version 1 and 2. XMF and Mobile XMF. Support for ringtone formats RTTTL/RTX, OTA, and iMelody | -Type 0 and 1 (.mid, .xmf, .mxmf). Also RTTTL/RTX (.rtttl, .rtx), OTA (.ota), and iMelody (.imy) | -|
| Ogg Vorbis | -- | X | -- | Ogg (.ogg) | -|
| PCM/WAVE | -- | X | -8- and 16-bit linear PCM (rates up to limit of hardware) | -WAVE (.wav) | -|
| Image | -JPEG | -X | -X | -base+progressive | -JPEG (.jpg) | -
| GIF | -- | X | -- | GIF (.gif) | -|
| PNG | -- | X | -- | PNG (.png) | -|
| BMP | -- | X | -- | BMP (.bmp) | -|
| Video | -H.263 | -X | -X | -- | 3GPP (.3gp) | -
| H.264 | -X | -X | -- | 3GPP (.3gp) and MPEG-4 (.mp4) | -|
| MPEG4 SP | -- | - | - | 3GPP (.3gp) | -
In addition to the core media formats supported in the Android platform, the T-Mobile G1 also supports the formats listed below.
- -| Type | -Format | -Encoder | -Decoder | -Details | -File Type(s) Supported | -
|---|---|---|---|---|---|
| Audio | -WMA | -- | X | -Supports WMA standard L1-L3:
-
|
-Windows Media Audio (.wma) | -
| Video | -WMV | -- | X | -Versions 7, 8 and 9. Simple profile only | -Windows Media Video (.wmv) | -
Note that Windows Media codecs are not part of the Android platform and require special licensing from Microsoft or an authorized developer such as Packet Video.
diff --git a/docs/html/guide/basics/appmodel.jd b/docs/html/guide/basics/appmodel.jd deleted file mode 100644 index 323fc9b..0000000 --- a/docs/html/guide/basics/appmodel.jd +++ /dev/null @@ -1,261 +0,0 @@ -page.title=Application Model -@jd:body -In most operating systems, there is a strong 1-to-1 correlation between -the executable image (such as the .exe on Windows) that an application lives in, -the process it runs in, and the icon and application the user interacts with. -In Android these associations are much more fluid, and it is important to -understand how the various pieces can be put together.
- -Because of the flexible nature of Android applications, there is some -basic terminology that needs to be understood when implementing the -various pieces of an application:
- -An android package (or .apk for short) -is the file containing an application's code and its resources. This is the -file that an application is distributed in and downloaded by the user when -installing that application on their device.
A task is generally what the user perceives as -an "application" that can be launched: usually a task has an icon in the -home screen through which it is accessed, and it is available as a top-level -item that can be brought to the foreground in front of other -tasks.
A process is a low-level kernel process in which -an application's code is running. Normally all of the code in a -.apk is run in one, dedicated process for that .apk; however, the -{@link android.R.styleable#AndroidManifestApplication_process process} tag -can be used to modify where that code is run, either for -{@link android.R.styleable#AndroidManifestApplication the entire .apk} -or for individual -{@link android.R.styleable#AndroidManifestActivity activity}, -{@link android.R.styleable#AndroidManifestReceiver receiver}, -{@link android.R.styleable#AndroidManifestService service}, or -{@link android.R.styleable#AndroidManifestProvider provider}, components.
A key point here is: when the user sees as an "application," what
-they are actually dealing with is a task. If you just create a .apk
-with a number of activities, one of which is a top-level entry point (via
-an {@link android.R.styleable#AndroidManifestIntentFilter intent-filter} for
-the action android.intent.action.MAIN and
-category android.intent.category.LAUNCHER), then there will indeed
-be one task created for your .apk, and any activities you start from there
-will also run as part of that task.
A task, then, from the user's perspective your application; and from the -application developer's perspective it is one or more activities the user -has traversed through in that task and not yet closed, or an activity stack. -A new task is created by -starting an activity Intent with the {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK -Intent.FLAG_ACTIVITY_NEW_TASK} flag; this Intent will be used as the root Intent of -the task, defining what task it is. Any activity started without this flag -will run in the same task as the activity that is starting it (unless that -activity has requested a special launch mode, as discussed later). Tasks can -be re-ordered: if you use FLAG_ACTIVITY_NEW_TASK but there is already a task -running for that Intent, the current task's activity stack will be brought -to the foreground instead of starting a new task.
- -FLAG_ACTIVITY_NEW_TASK must only be used with care: using it says that, -from the user's perspective, a new application starts at this point. If this -is not the behavior you desire, you should not be creating a new task. In -addition, you should only use the new task flag if it is possible for the user -to navigate from home back to where they are and launch the same Intent as a -new task. Otherwise, if the user presses HOME instead of BACK from the task -you have launched, your task and its activities will be ordered behind the -home screen without a way to return to them.
- -In some cases Android needs to know which task an activity belongs to even when -it is not being launched in to a specific task. This is accomplished through -task affinities, which provide a unique static name for the task that one or more -activities are intended to run in. The default task affinity for an activity -is the name of the .apk package name the activity is implemented in. This -provides the normally expected behavior, where all of the activities in a -particular .apk are part of a single application to the user.
- -When starting a new activity without the -{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK -Intent.FLAG_ACTIVITY_NEW_TASK} flag, task affinities have no impact on the -task the new activity will run in: it will always run in the task of the -activity that is starting it. However, if the NEW_TASK flag is being used, -then the affinity will be used to determine if a task already exists with -the same affinity. If so, that task will be brought to the front and the -new activity launched at the top of that task.
- -This behavior is most useful for situations where you must use the -NEW_TASK flag, in particular launching activities from status bar notifications -or home screen shortcuts. The result is that, when the user launches your -application this way, its current task state will be brought to the foreground, -and the activity they now want to look at placed on top of it.
- -You can assign your own task affinities in your manifest's -{@link android.R.styleable#AndroidManifestApplication application} tag for -all activities in the .apk, or the -{@link android.R.styleable#AndroidManifestActivity activity} tag of -individual activities. Some examples of how this can be used are:
- -The main way you control how activities interact with tasks is through -the activity's -{@link android.R.styleable#AndroidManifestActivity_launchMode launchMode} -attribute and the {@link android.content.Intent#setFlags flags} associated -with an Intent. These two parameters can work together in various ways -to control the outcome of the activity launch, as described in their -associated documentation. Here we will look at some common use cases and -combinations of these parameters.
- -The most common launch mode you will use (besides the default
-standard mode) is singleTop. This does not have
-an impact on tasks; it just avoids starting the same activity multiple times
-on the top of a stack.
-
-
The singleTask launch mode has a major
-impact on tasks: it causes the activity to always be started in
-a new task (or its existing task to be brought to the foreground). Using
-this mode requires a lot of care in how you interact with the rest of the
-system, as it impacts every path in to the activity. It should only be used
-with activities that are front doors to the application (that is, which
-support the MAIN action and LAUNCHER category).
The singleInstance launch mode is even more specialized, and
-should only be used in applications that are implemented entirely as one
-activity.
A situation you will often run in to is when another entity (such as the -{@link android.app.SearchManager} or {@link android.app.NotificationManager}) -starts one of your activities. In this case, the -{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK -Intent.FLAG_ACTIVITY_NEW_TASK} flag must be used, because the activity is -being started outside of a task (and the application/task may not even -exist). As described previously, the standard behavior in this situation -is to bring to the foreground the current task matching the new activity's -affinity and start the new activity at the top of it. There are, however, -other types of behavior that you can implement.
- -One common approach is to also use the
-{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP
-Intent.FLAG_ACTIVITY_CLEAR_TOP} flag in conjunction with NEW_TASK. By doing so,
-if your task is already running, then it will be brought to the foreground,
-all of the activities on its stack cleared except the root activity, and the
-root activity's {@link android.app.Activity#onNewIntent} called with the
-Intent being started. Note that the activity often also use the singleTop
-or singleTask launch mode when using this approach, so that
-the current instance is given the new intent instead of requiring that it
-be destroyed and a new instance started.
Another approach you can take is to set the notification activity's
-android:taskAffinity to the empty string "" (indicating no affinity)
-and setting the
-{@link android.R.styleable#AndroidManifestActivity_noHistory
-android:noHistory} and
-{@link android.R.styleable#AndroidManifestActivity_excludeFromRecents
-android:excludeFromRecents} attributes.
-This approach is useful if you would like the notification
-to take the user to a separate activity describing it, rather than return
-to the application's task. By specifying these attributes, the activity will
-be finished whether the user leaves it with BACK or HOME and it will not
-show up in the recent tasks list; if the noHistory attribute
-isn't specified, pressing HOME will result in the activity and its task
-remaining in the system, possibly with no way to return to it.
Be sure to read the documentation on the -{@link android.R.styleable#AndroidManifestActivity_launchMode launchMode attribute} -and the {@link android.content.Intent#setFlags Intent flags} for the details -on these options.
- -In Android, processes are entirely an implementation detail of applications -and not something the user is normally aware of. Their main uses are simply:
- -As described previously, the -{@link android.R.styleable#AndroidManifestApplication_process process} attribute -is used to control the process that particular application components run in. -Note that this attribute can not be used to violate security of the system: if -two .apks that are not sharing the same user ID try to run in the same process, -this will not be allowed and different distinct processes will be created for -each of them.
- -See the security document for -more information on these security restrictions.
- -Every process has one or more threads running in it. In most situations, Android -avoids creating additional threads in a process, keeping an application -single-threaded unless it creates its own threads. An important repercussion -of this is that all calls to {@link android.app.Activity}, -{@link android.content.BroadcastReceiver}, and {@link android.app.Service} -instances are made only from the main thread of the process they are running in.
- -Note that a new thread is not created for each -Activity, BroadcastReceiver, Service, or ContentProvider instance: -these application components are instantiated in the desired process (all in the -same process unless otherwise specified), in the main thread of that process. -This means that none of these components (including services) should perform -long or blocking operations (such as networking calls or computation loops) -when called by the system, since this will block -all other components in the process. You can use the standard library -{@link java.lang.Thread} class or Android's {@link android.os.HandlerThread} -convenience class to perform long operations on another thread.
- -There are a few important exceptions to this threading rule:
- -Calls on to an {@link android.os.IBinder} or interface implemented on -an IBinder are dispatched from the thread calling them or a thread pool in the -local process if coming from another process, not -from the main thread of their process. In particular, calls on to the IBinder -of a {@link android.app.Service} will be called this way. (Though -calls to methods on Service itself are done from the main thread.) -This means that implementations of IBinder interfaces must always be -written in a thread-safe way, since they can be called from any number of -arbitrary threads at the same time.
Calls to the main methods of {@link android.content.ContentProvider} -are dispatched from the calling thread or main thread as with IBinder. The -specific methods are documented in the ContentProvider class. -This means that implementations of these methods must always be -written in a thread-safe way, since they can be called from any number of -arbitrary threads at the same time.
Calls on {@link android.view.View} and its subclasses are made from the -thread that the view's window is running in. Normally this will be the main -thread of the process, however if you create a thread and show a window from -there then the window's view hierarchy will be called from that thread.
You can think of an Android application as a collection of components, of -various kinds. These components are for the most part quite loosely coupled, -to the degree where you can accurately describe them as a federation of -components rather than a single cohesive application.
- -Generally, these components all run in the same system process. It's -possible (and quite common) to create multiple threads within that process, -and it's also possible to create completely separate child processes if you -need to. Such cases are pretty uncommon though, because Android tries very -hard to make processes transparent to your code.
- -These are the most important parts of the Android APIs:
- -To get started with Android, please read the following sections first:
-After reading the sections above, the following Getting Started information is also very useful:
- - -These are the basic packages that make up the Android SDK for writing -applications. The packages are organized as layers, listed here from -lowest-level to highest.
- -These packages provide additional domain-specific features of the Android -platform. They are not necessary for basic application development.
- -Android is a software stack for mobile devices that includes an operating -system, middleware and key applications. The Android SDK -provides the tools and APIs necessary to begin developing applications on the -Android platform using the Java programming language.
- -The following diagram shows the major components of the Android operating -system. Each section is described in more detail below.
- -
Android will ship with a set of core applications including an email -client, SMS program, calendar, maps, browser, contacts, and -others. All applications are written using the Java programming language.
- - -Developers have full access to the same framework APIs used by the core -applications. The application architecture is designed to simplify the reuse -of components; any application can publish its capabilities and any other -application may then make use of those capabilities (subject to security -constraints enforced by the framework). This same mechanism allows components -to be replaced by the user.
- -Underlying all applications is a set of services and systems, including: -
For more details and a walkthrough of an application, see the Notepad Tutorial.
- - -Android includes a set of C/C++ libraries used by various components of the -Android system. These capabilities are exposed to developers through the -Android application framework. Some of the core libraries are listed below:
-Android includes a set of core libraries that provides most of -the functionality available in the core libraries of the Java programming -language.
- -Every Android application runs in its own process, with its own instance of -the Dalvik virtual machine. Dalvik has been written so that a device can run -multiple VMs efficiently. The Dalvik VM executes files in the Dalvik -Executable (.dex) format which is optimized for minimal memory -footprint. The VM is register-based, and runs classes -compiled by a Java language compiler that have been transformed into the .dex -format by the included "dx" tool.
- -The Dalvik VM relies on the Linux kernel for underlying functionality such -as threading and low-level memory management.
- - - -Android relies on Linux version 2.6 for core system services such as -security, memory management, process management, network stack, and driver -model. The kernel also acts as an abstraction layer between the hardware and -the rest of the software stack.
diff --git a/docs/html/guide/developing/app-signing.jd b/docs/html/guide/developing/app-signing.jd deleted file mode 100644 index 582dfb2..0000000 --- a/docs/html/guide/developing/app-signing.jd +++ /dev/null @@ -1,428 +0,0 @@ -page.title=Signing Your Applications -@jd:body - -The Android system requires that all installed applications be digitally -signed with a certificate whose private key is held by the application's -developer. The system uses the certificate as a means of identifying the author of -an application and establishing trust relationships between applications, rather -than for controlling which applications the user can install. The certificate -does not need to be signed by a certificate authority: it is perfectly -allowable, and typical, for Android applications to use self-signed -certificates.
- -The important points to understand about signing Android applications are:
- -The Android system will not install or run an application that is not signed appropriately. This -applies wherever the Android system is run, whether on an actual device or on the emulator. -For this reason, you must set up signing for your application before you will be able to -run or debug it on an emulator or device.
- -The Android SDK tools assist you in signing your applications when debugging. Both the ADT Plugin -for Eclipse and the Ant build tool offer two signing modes — debug mode and release mode. - -
Some aspects of application signing may affect how you approach the development -of your application, especially if you are planning to release multiple -applications.
- -In general, the recommended strategy for all developers is to sign -all of your applications with the same certificate, throughout the expected -lifespan of your applications. There are several reasons why you should do so:
- -Another important consideration in determining your signing strategy is -how to set the validity period of the key that you will use to sign your -applications.
- -As you design your application, keep these points in mind and make sure to -use a suitable certificate to sign your applications.
- -To support the generation of a keystore and debug key, you should first make sure that -Keytool is available to the SDK build -tools. In most cases, you can tell the SDK build tools how to find Keytool by making sure -that your JAVA_HOME environment variable is set and that it references a suitable JDK. -Alternatively, you can add the JDK version of Keytool to your PATH variable.
- -If you are developing on a version of Linux that originally came with GNU Compiler for -Java, make sure that the system is using the JDK version of Keytool, rather than the gcj -version. If Keytool is already in your PATH, it might be pointing to a symlink at -/usr/bin/keytool. In this case, check the symlink target to make sure that it points -to the Keytool in the JDK.
- -If you will release your application to the public, you will also need to have -the Jarsigner tool available on your machine. Both Jarsigner and Keytool are included -in the JDK.
- -The Android build tools provide a debug signing mode that makes it easier for you -to develop and debug your application, while still meeting the Android system -requirement for signing your .apk when it is installed in the emulator or a device.
- -If you are developing in Eclipse/ADT and have set up Keytool as described -above, signing in debug mode is enabled by default. When you run or debug your -application, ADT signs the .apk for you and installs it on the emulator. No -specific action on your part is needed, provided ADT has access to Keytool.
- -If you use Ant to build your .apk files, debug signing mode -is enabled by default, assuming that you are using a build.xml file generated by the -activitycreator tool included in the latest SDK. When you run Ant against build.xml to -compile your app, the build script generates a keystore/key and signs the .apk for you. -No specific action on your part is needed.
- -Note that you can not release your application to the public if it is signed only with -the debug key.
- -When your application is ready for release to other users, you must:
-The sections below provide information about these steps.
- -To prepare your application for release, you must first compile it in release mode. -In release mode, the Android build tools compile your application as usual, -but without signing it with the debug key.
- -If you are developing in Eclipse/ADT, right-click the project in the Package -pane and select Android Tools > Export Application -Package. You can then specify the file location for the unsigned .apk. -Alternatively, you can follow the "Exporting the unsigned .apk" -link in the Manifest Editor overview page.
- -If you are using Ant, all you need to do is specify the build target -"release" in the Ant command. For example, if you are running Ant from the -directory containing your build.xml file, the command would look like this:
- -$ ant release- -
The build script compiles the application .apk without signing it. - -
Note that you can not release your application unsigned, or signed with the debug key.
- -In preparation for signing your application, you must first ensure that -you have a suitable private key with which to sign. A suitable private -key is one that:
- -If you plan to publish your application(s) on Android Market, note that a -validity period ending after 22 October 2033 is a requirement. You can not upload an -application if it is signed with a key whose validity expires before that date. -
The key may be self-signed. If you do not have a suitable key, you must -generate one using Keytool. Make sure that you have Keytool available, as described -in Basic Setup.
- -To generate a self-signed key with Keytool, use the keytool
-command and pass any of the options listed below (and any others, as
-needed).
Before you run Keytool, make sure to read Securing Your Key for a discussion of how to keep your -key secure and why doing so is critically important to you and to users. In -particular, when you are generating your key, you should select strong -passwords for both the keystore and key.
- -| Keytool Option | -Description | -
|---|---|
-genkey | Generate a key pair (public and private -keys) | -
-v | Enable verbose output. | -
-keystore <keystore-name>.keystore | A name -for the keystore containing the private key. | -
-storepass <password> | A password for the -keystore. As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
-alias <alias_name> | An alias for the key. | -
-keyalg <alg> | The encryption algorithm to use -when generating the key. | -
-dname <name> | A Distinguished Name that describes -who created the key. The value is used as the issuer and subject fields in the -self-signed certificate. Note that you do not need to specify this option -in the command line. If not supplied, Jarsigner prompts you to enter each -of the Distinguished Name fields (CN, OU, and so on). |
-
-validity <valdays> | The validity period for the -key, in days. Note: A value of 9500 or greater is recommended. |
-
-keypass <password> | The password for the key. -As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
Here's an example of a Keytool command that generates a private key:
- -$ keytool -genkey -v -keystore my-release-key.keystore --alias alias_name -keyalg RSA -validity 9500- -
Running the example command above, Keytool prompts you to provide
-passwords for the keystore and key, and to provide the Distinguished
-Name fields for your key. It then generates the keystore as a file called
-my-release-key.keystore. The keystore and key are
-protected by the passwords you entered. The keystore contains
-a single key, valid for 9500 days. The alias is a name that you —
-will use later, to refer to this keystore when signing your application.
For more information about Keytool, see the documentation at - -http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security
- -When you are ready to actually sign your .apk for release, you can do so -using the Jarsigner tool. Make sure that you have Jarsigner available on your -machine, as described in Basic Setup. Also, make sure that -the keystore containing your private key is available.
- -To sign your application, you run Jarsigner, referencing both the -application's .apk and the keystore containing the private key with which to -sign the .apk. The table below shows the options you could use.
- -
| Jarsigner Option | -Description | -
|---|---|
-keystore <keystore-name>.keystore | The name of -the keystore containing your private key. | -
-verbose | Enable verbose output. | -
-storepass <password> | The password for the -keystore. As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Jarsigner prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
-keypass <password> | The password for the private -key. As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Jarsigner prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
Here's how you would use Jarsigner to sign an application package called
-my_application.apk, using the example keystore created above.
-
$ jarsigner -verbose -keystore my-release-key.keystore -my_application.apk alias_name- -
Running the example command above, Jarsigner prompts you to provide -passwords for the keystore and key. It then modifies the APK -in-place, meaning the .apk is now signed. Note that you can sign an -APK multiple times with different keys.
- -To verify that your .apk is signed, you can use a command like this:
- -$ jarsigner -verify my_signed.apk- -
If the .apk is signed properly, Jarsigner prints "jar verified". -If you want more details, you can try one of these commands:
- -$ jarsigner -verify -verbose my_application.apk- -
or
- -$ jarsigner -verify -verbose -certs my_application.apk- -
The command above, with the -certs option added, will show you the
-"CN=" line that describes who created the key.
Note: if you see "CN=Android Debug", this means the .apk was -signed with the debug key generated by the Android SDK. If you intend to release -your application, you must sign it with your private key instead of the debug -key.
- -For more information about Jarsigner, see the documentation at - -http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security
- -Maintaining the security of your private key is of critical importance, both -to you and to the user. If you allow someone to use your key, or if you leave -your keystore and passwords in an unsecured location such that a third-party -could find and use them, your authoring identity and the trust of the user -are compromised.
- -If a third party should manage to take your key without your knowledge or -permission, that person could sign and distribute applications that maliciously -replace your authentic applications or corrupt them. Such a person could also -sign and distribute applications under your identity that attack other -applications or the system itself, or corrupt or steal user data.
- -Your reputation as a developer entity depends on your securing your private -key properly, at all times, until the key is expired. Here are some tips for -keeping your key secure:
- --storepass and -keypass options at the command line.
-If you do so, your passwords will be available in your shell history,
-which any user on your computer could access.-storepass and -keypass
-options at the command line. In general, if you follow common-sense precautions when generating, using, -and storing your key, it will remain secure.
- -The self-signed certificate used to sign your application in debug mode (the default on -Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.
- -When the certificate expires, you will get a build error. On Ant builds, the error -looks like this:
- -debug: -[echo] Packaging bin/samples-debug.apk, and signing it with a debug key... -[exec] Debug Certificate expired on 8/4/08 3:43 PM- -
In Eclipse/ADT, you will see a similar error in the Android console.
- -To fix this problem, simply delete the debug.keystore file. On Linux/Mac OSX,
-the file is stored in ~/.android. OOn Windows XP, the file is stored in
-C:\Documents and Settings\<user>\Local Settings\Application Data\Android.
-On Windows Vista, the file is stored in
-C:\Users\<user>\AppData\Local\Android.
The next time you build, the build tools will regenerate a new keystore and debug key.
- -Note that, if your development machine is using a non-Gregorian locale, the build -tools may erroneously generate an already-expired debug certificate, so that you get an -error when trying to compile your application. For workaround information, see the -troubleshooting topic -I can't compile my app because the build tools generated an expired debug -certificate.
\ No newline at end of file diff --git a/docs/html/guide/developing/debug-tasks.jd b/docs/html/guide/developing/debug-tasks.jd deleted file mode 100644 index 6b7c27a..0000000 --- a/docs/html/guide/developing/debug-tasks.jd +++ /dev/null @@ -1,207 +0,0 @@ -page.title=Debugging Tasks -@jd:body - -This document offers some helpful guidance to debugging applications on Android. - - -
The Android SDK includes a fairly extensive set of tools to help you debug your programs:
-...
-I/MemoryDealer( 763): MemoryDealer (this=0x54bda0): Creating 2621440 bytes heap at 0x438db000
-I/Logger( 1858): getView() requesting item number 0
-I/Logger( 1858): getView() requesting item number 1
-I/Logger( 1858): getView() requesting item number 2
-D/ActivityManager( 763): Stopping: HistoryRecord{409dbb20 com.android.home.AllApps}
-...
-
- {@link android.util.Log Android Log}- A logging - class to print out messages to a log file on the emulator. You can read messages - in real time if you run logcat on DDMS (covered next). Add a few logging - method calls to your code.
-To use the Log class, you just call Log.v()
- (verbose), Log.d() (debug), Log.i() (information),
- Log.w() (warning) or Log.e (error) depending
- on the importance you wish to assign the log message.
Log.i("MyActivity", "MyClass.getView()
- — Requesting item number " + position)
- You can use logcat to read these messages
Also, see the Troubleshooting section - of the doc to figure out why your application isn't appearing on the emulator, - or why it's not starting.
- - -With the Dev Tools application, you can turn on a number of settings that will make it easier to test - and debug your applications. To get to the development settings page on the emulator, launch the - Dev Tools application and open Development Settings. - This will open the development settings page with the following options (among - others):
-These settings will be remembered across emulator restarts.
- -adb shell, use "ps" to find the process you
-want, and then "kill -3 ". The stack trace appears in the log file.
--adb shell -logcat -b radio --
DDMS will assign a specific debugging port to every virtual machine that it - finds on the emulator. You must either attach your IDE to that - port (listed on the Info tab for that VM), or you can use a default port 8700 - to connect to whatever application is currently selected on the list of discovered - virtual machines.
-Your IDE should attach to your application running on the emulator, showing you - its threads and allowing you to suspend them, inspect their state, and set breakpoints. - If you selected "Wait for debugger" in the Development settings panel - the application will run when Eclipse connects, so you will need to set any breakpoints - you want before connecting.
-Changing either the application being debugged or the "Wait for debugger" - option causes the system to kill the selected application if it is currently - running. You can use this to kill your application if it is in a bad state - by simply going to the settings and toggling the checkbox.
diff --git a/docs/html/guide/developing/device.jd b/docs/html/guide/developing/device.jd deleted file mode 100644 index 35c0a1a..0000000 --- a/docs/html/guide/developing/device.jd +++ /dev/null @@ -1,163 +0,0 @@ -page.title=Developing on a Device -@jd:body - -When building mobile applications, it's vital to test them on real -devices prior to releasing them to users. This page covers what you need to know, -including the types of devices that you can use, and how to set one up for -developing and debugging.
- - -While developers can use regular -consumer devices purchased at retail to test and use their apps, some developers -may choose not to use a retail device, preferring an unlocked or no-contract -device. Here are some options for obtaining devices capable of testing your applications.
- - -The T-Mobile G1 device makes an excellent development device. You can write -applications in the SDK and install them on the G1, then run them as users -would, using the same hardware, system, and network.
- -For more information about obtaining a G1, visit the T-Mobile G1 site.
- - -Selected specs for Android Dev Phone 1:
-The Android Dev Phone 1 is a SIM-unlocked and hardware-unlocked device that -is designed for advanced developers. The device ships with a system image that -is fully compatible with Android 1.0, so you can rely on it when developing your -applications. You can use any SIM in the device and can flash custom Android -builds that will work with the unlocked bootloader. Unlike the bootloader on -retail devices, the bootloader on the Android Dev Phone 1 does not enforce -signed system images. The Android Dev Phone 1 should also appeal to developers -who live outside of T-Mobile geographies.
- -To purchase an Android Dev Phone 1 device, you must first register as an -Android developer on the Android Market site, if you haven't done so already. -Once you've logged into your developer account on Android Market, you can -purchase the device by following the link to "Development phones." To accommodate demand, -there is a limit of 1 device per developer account, for now.
- -The device currently costs $399 (USD) (including free shipping in the US), -and is available for purchase in 18 international markets, including the -US, UK, Germany, Japan, India, Canada, France, Taiwan, Spain, Australia, -Singapore, Switzerland, Netherlands, Austria, Sweden, Finland, Poland, and -Hungary. We will continue to expand this program into new geographies over -time. Check this page for updated information.
- -Note that Android Dev Phone 1 devices are not intended for -non-developer end-users. Because the device can be configured with system -software not provided by or supported by Google or any other company, end-users -operate these devices at their own risk.
- -For full device specs and more information about obtaining an Android Dev -Phone 1 device, see the Android -Market site.
- - -With a T-mobile G1 or Android Dev Phone 1, you can develop and debug your Android applications just as you -would on the emulator. There are just a few things to do before you can start.
-In Eclipse, you can do this from the Application tab when viewing the Manifest
- (on the right side, set Debuggable to true). Otherwise, in the AndroidManifest.xml
-
- file, add android:debuggable="true" to the <application> element.
On the device, go to the home screen, press MENU, select Applications > Development, - then enable USB debugging.
- -usb_driver/x86 in the SDK package (<sdk>\usb_driver\x86).usb_driver/amd64 in the SDK package (<sdk>\usb_driver\amd64)./etc/udev/rules.d/50-android.rules.
- For Gusty/Hardy, edit the file to read:
- SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"
For Dapper, edit the file to read:
- SUBSYSTEM=="usb_device", SYSFS{idVendor}=="0bb4", MODE="0666"
chmod a+rx /etc/udev/rules.d/50-android.rules
- You can verify that your device is connected by executing adb devices from your
-SDK tools/ directory. If connected, you'll see the device name listed as a "device."
If using Eclipse, select run or debug as usual. You will be presented -with a Device Chooser dialog that lists the available emulator(s) and connected device(s). -Select the device to install and run the application there.
- -If using the Android Debug Bridge (adb),
-you can issue commands with the -d flag to target your connected device.
The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse integrated development environment. It allows you to create and debug Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications:
- -To begin developing Android applications in the Eclipse IDE with ADT, you first need to download the Eclipse IDE and then download and install the ADT plugin. To do so, follow the steps given in Installing the ADT Plugin, in the installation documentation included with your SDK package.
- -Once you've installed the ADT plugin, you begin by creating an Android -project and then set up a launch configuration. After that, you can write, run, and debug -your application.
- -The sections below provide instructions assuming that you have installed the ADT plugin -in your Eclipse environment. If you haven't installed the ADT plugin, you should do that -before using the instructions below.
- - - -The ADT plugin provides a New Project Wizard that you can use to quickly create an -Eclipse project for new or existing code. To create the project, follow these steps:
- - - -Enter the project name, the base package name, the name of a single Activity class to create as a stub .java file, and a name to use for your application.
Browse to the directory containing the existing source code and click OK. If the directory contains a valid Android manifest file, the ADT plugin fills in the package, activity, and application names for you.
-The ADT plugin creates the these folders and - files for you as appropriate for the type of project:
- -Before you can run and debug your application in Eclipse, you must create a launch configuration for it. A launch configuration specifies the project to launch, the Activity to start, the emulator options to use, and so on.
- -To create a launch configuration for the application, follow these steps as appropriate for your Eclipse version:
- -As you begin developing Android applications, you should understand that all -Android applications must be digitally signed before the system will install -them on the emulator or an actual device.
- -The ADT plugin helps you get started quickly by signing your .apk files with -a debug key, prior to installing them on the emulator. This means that you can -compile your application and install it on the emulator without having to -generate your own private key. However, please note that if you intend to -publish your application, you must sign the application with your own -private key, rather than the debug key generated by the SDK tools.
- -To sign your applications, the ADT plugin requires the Keytool utility -included in the JDK. To set up your development environment for -signing, you need to make sure that Keytool is available on your -machine that the ADT plugin knows how to find it.
- -In most cases, you can tell the SDK build tools how to find Keytool by making -sure that your JAVA_HOME environment variable is set and that it references a -suitable JDK. Alternatively, you can add the JDK version of Keytool to your -PATH variable.
- -If you are developing on a version of Linux that originally came with Gnu -Compiler for Java, make sure that the system is using the JDK version of -Keytool, rather than the gcj version. If keytool is already in your PATH, it -might be pointing to a symlink at /usr/bin/keytool. In this case, check the -symlink target to make sure that it points to the keytool in the JDK.
- -In all cases, please read and understand Signing Your -Applications, which provides an overview of application signing on Android -and what it means to you as an Android application developer.
- - - - -Once you've set up the project and launch configuration for your application, you can run or debug it as described below.
- -From the Eclipse main menu, select Run > Run or Run > Debug as appropriate, to run or debug the active launch configuration. - -Note that the active launch configuration is the one most recently selected in the Run configuration manager. It does not necessarily correspond to the application that is selected in the Eclipse Navigation pane (if any).
- -To set or change the active launch configuration, use the launch configuration manager. See Creating a Launch Configuration for information about how to access the launch configuration manager..
- -Running or debugging the application triggers these actions:
-You can execute arbitrary code when paused at a breakpoint in Eclipse. For example,
- when in a function with a String argument called "zip", you can get
- information about packages and call class methods. You can also invoke arbitrary
- static methods: for example, entering android.os.Debug.startMethodTracing() will
- start dmTrace.
Open a code execution window, select Window>Show - View>Display from the main menu to open the - Display window, a simple text editor. Type your expression, highlight the - text, and click the 'J' icon (or CTRL + SHIFT + D) to run your - code. The code runs in the context of the selected thread, which must be - stopped at a breakpoint or single-step point. (If you suspend the thread - manually, you have to single-step once; this doesn't work if the thread is - in Object.wait().)
-If you are currently paused on a breakpoint, you can simply highlight and execute - a piece of source code by pressing CTRL + SHIFT + D.
-You can highlight a block of text within the same scope by pressing ALT +SHIFT - + UP ARROW to select larger and larger enclosing blocks, or DOWN ARROW to select - smaller blocks.
-Here are a few sample inputs and responses in Eclipse using the Display window.
-| Input | -Response | -
|---|---|
zip |
- (java.lang.String) /work/device/out/linux-x86-debug/android/app/android_sdk.zip |
-
zip.endsWith(".zip") |
- (boolean) true |
-
zip.endsWith(".jar") |
- (boolean) false |
-
You can also execute arbitrary code when not debugging by using a scrapbook page. - Search the Eclipse documentation for "scrapbook".
- -Although the recommended way to debug is to use the ADT plugin, you can manually run DDMS and configure Eclipse to debug on port 8700. (Note: Be sure that you have first started DDMS).
diff --git a/docs/html/guide/developing/index.html b/docs/html/guide/developing/index.html deleted file mode 100644 index 4881acf..0000000 --- a/docs/html/guide/developing/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/developing/other-ide.jd b/docs/html/guide/developing/other-ide.jd deleted file mode 100644 index 7bcb509..0000000 --- a/docs/html/guide/developing/other-ide.jd +++ /dev/null @@ -1,167 +0,0 @@ -page.title=In Other IDEs -@jd:body - -The recommended way to develop an Android application is to use - Eclipse with the Android - Development Tools (ADT) plugin, provided in the SDK. The ADT plugin - provides editing, building,and debugging functionality integrated right into the IDE.
- -However, if you'd rather develop your application in another IDE, such as IntelliJ, - or use Eclipse without the ADT plugin, you can do that instead. The SDK - provides the tools you need to set up, build, and debug your application. -
- - -The Android SDK includes activityCreator, a program that generates a number of stub files for your project, as well as a build file. You can use the program to create an Android project for new code or from existing code, such as the sample applications included in the SDK. For Linux and Mac, the SDK provides activitycreator and for Windows, activityCreator.bat, a batch script. Regardless of platform, you can use activitycreator in the same way.
To run activityCreator and create an Android project, follow these steps:
tools/ directory of the SDK and create a new directory for your project files. If you are creating a project from existing code, change to the root folder of your application instead. Run activityCreator. In the command, you must specify a fully-qualified class name as an argument. If you are creating a project for new code, the class represents the name of a stub class that the script will create. If you are creating a project from existing code, you must specify the name of one Activity class in the package. Command options for the script include:
-
--out <folder> which sets the output directory. By default, the output directory is the current directory. If you created a new directory for your project files, use this option to point to it. --ide intellij, which generates IntelliJ IDEA project files in the newly created projectHere's an example:
--~/android_linux_sdk/tools $ ./activityCreator.py --out myproject your.package.name.ActivityName -package: your.package.name -out_dir: myproject -activity_name: ActivityName -~/android_linux_sdk/tools $- -
The activityCreator script generates the following files and directories (but will not overwrite existing ones):
AndroidManifest.xml The application manifest file, synced to the specified Activity class for the project.build.xml An Ant file that you can use to build/package the application.src/your/package/name/ActivityName.java The Activity class you specified on input.your_activity.iml, your_activity.ipr,
- your_activity.iws [only
- with the -ide intelliJ flag] intelliJ project
- files. res/ A directory to hold resources. src/ The source directory.
- bin/ The output directory for the build script.You can now move your folder wherever you want for development, but keep in mind
- that you'll have to use the adb program in the tools/ folder to
- send files to the emulator, so you'll need access between your solution and
- the tools/ folder.
Also, you should refrain from moving the - location of the SDK directory, since this will break the build scripts (they - will need to be manually updated to reflect the new SDK location before they will - work again).
- -Use the Ant build.xml file generated by
- activityCreator to build your application.
Note: When installing JDK on Windows, the default is to install in the "Program Files" directory. This location will cause ant to fail, because of the space. To fix the problem, you can specify the JAVA_HOME variable like this: set JAVA_HOME=c:\Prora~1\Java\. The easiest solution, however, is to install JDK in a non-space directory, for example: c:\java\jdk1.6.0_02.
As you begin developing Android applications, you should understand that all -Android applications must be digitally signed before the system will install -them on the emulator or an actual device.
- -The Android build tools help you get started quickly by signing your .apk -files with a debug key, prior to installing them on the emulator. This means -that you can compile your application and install it on the emulator without -having to generate your own private key. However, please note that if you intend -to publish your application, you must sign the application with your -own private key, rather than the debug key generated by the SDK tools.
- -To sign your applications, the ADT plugin requires the Keytool utility -included in the JDK. To set up your development environment for -signing, all you need to do is make sure that Keytool is available on your -machine that the build tools know how to find it.
- -In most cases, you can tell the SDK build tools how to find Keytool by making -sure that -your JAVA_HOME environment variable is set and that it references a suitable -JDK. Alternatively, -you can add the JDK version of Keytool to your PATH variable.
- -If you are developing on a version of Linux that originally came with Gnu -Compiler for Java, -make sure that the system is using the JDK version of Keytool, rather than the -gcj version. -If keytool is already in your PATH, it might be pointing to a symlink at -/usr/bin/keytool. -In this case, check the symlink target to make sure that it points to the -keytool in the JDK.
- -In all cases, please read and understand Signing Your -Applications, which provides an overview of application signing on Android -and what it means to you as an Android application developer.
- - -To run a compiled
- application, you will upload the .apk file to the /data/app/ directory
- in the emulator using the adb tool as described here:
<your_sdk_dir>/tools/emulator from the command line)adb install myproject/bin/<appname>.apk to upload
- the executable. So, for example, to install the Lunar Lander sample, navigate
- in the command line to <your_sdk_dir>/sample/LunarLander and type ../../tools/adb install bin/LunarLander.apkNote: When you install an Activity for the - first time, you might have to restart the emulator before it shows up in the - application launcher, or other applications can call it. This is because - the package manager usually only examines manifests completely on emulator - startup.
- -This section describes how to display debug information on the screen (such - as CPU usage), as well as how to hook up your IDE to debug running applications - on the emulator.
- -Attaching a debugger is automated using the Eclipse plugin, - but you can configure other IDEs to listen on a debugging port to receive debugging - information.
-aapt stands for Android Asset Packaging Tool and is included in the tools/ directory of the SDK. This tool allows you to view, create, and update Zip-compatible archives (zip, jar, apk). It can also compile resources into binary assets.
-
-Though you probably won't often use aapt directly, build scripts and IDE plugins can utilize this tool to package the apk file that constitutes an Android application. -
-
-For more usage details, open a terminal, go to the tools/ directory, and run the command:
-
Linux or Mac OS X:
-./aapt-
Windows:
-aapt.exe-
Android Debug Bridge (adb) is a versatile tool lets you manage the state of an emulator instance or Android-powered device. It is a client-server program that includes three components:
- -When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.
- -The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:
- --Emulator 1, console: 5554- -
-Emulator 1, adb: 5555
-Emulator 2, console: 5556
-Emulator 2, adb: 5557 ... -
As shown, the emulator instance connected to adb on port 5555 is the same as the instance whose console listens on port 5554.
- -Once the server has set up connections to all emulator instances, you can use adb commands to control and access those instances. Because the server manages connections to emulator/device instances and handles commands from multiple adb clients, you can control any emulator/device instance from any client (or from a script).
- -The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a trasparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.
- - - -You can issue adb commands from a command line on your development machine or from a script. The usage is:
- -adb [-d|-e|-s <serialNumber>] <command>- -
When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.
Before issuing adb commands, it is helpful to know what emulator/device instances are connected to the adb server. You can generate a list of attached emulators/devices using the devices command:
adb devices- -
In response, adb prints this status information for each instance:
- -<type>-<consolePort>.
- Here's an example serial number: emulator-5554offline — the instance is not connected to adb or is not responding.device — the instance is now connected to the adb server. Note that this state does not
- imply that the Android system is fully booted and operational, since the instance connects to adb
- while the system is still booting. However, after boot-up, this is the normal operational state of
- an emulator/device instance.The output for each instance is formatted like this:
- -[serialNumber] [state]- -
Here's an example showing the devices command and its output:
$ adb devices -List of devices attached -emulator-5554 device -emulator-5556 device -emulator-5558 device- -
If there is no emulator/device running, adb returns no device.
If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:
adb -s <serialNumber> <command>- -
As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the devices command to obtain the serial numbers of running emulator/device instances.
Here is an example:
- -adb -s emulator-5556 install helloWorld.apk- -
Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error.
-
-
-
-
You can use adb to copy an application from your development computer and install it on an emulator/device instance. To do so, use the install command. With the command, you must specify the path to the .apk file that you want to install:
adb install <path_to_apk>- -
For more information about how to create an .apk file that you can install on an emulator/device instance, see Android Asset Packaging Tool (aapt).
- -Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you.
- - - - -You can use the forward command to set up arbitrary port forwarding — forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:
adb forward tcp:6100 tcp:7100-
You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:
-adb forward tcp:6100 local:logd- - - -
You can use the adb commands pull and push to copy files to and from an emulator/device instance's data file. Unlike the install command, which only copies an .apk file to a specific location, the pull and push commands let you copy arbitrary directories and files to any location in an emulator/device instance.
To copy a file or directory (recursively) from the emulator or device, use
-adb pull <remote> <local>- -
To copy a file or directory (recursively) to the emulator or device, use
-adb push <local> <remote>- -
In the commands, <local> and <remote> refer to the paths to the target files/directory on your development machine (local) and on the emulator/device instance (remote).
Here's an example:
-adb push foo.txt /sdcard/foo.txt- - - -
The table below lists all of the supported adb commands and explains their meaning and usage.
- - -| Category | -Command | -Description | -Comments | -
|---|---|---|---|
| Options | --d |
-Direct an adb command to the only attached USB device. | -Returns an error if more than one USB device is attached. | -
-e |
-Direct an adb command to the only running emulator instance. | -Returns an error if more than one emulator instance is running. | -|
-s <serialNumber> |
-Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556"). | -If not specified, adb generates an error. | -|
| General | -devices |
-Prints a list of all attached emulator/device instances. | -See Querying for Emulator/Device Instances for more information. | -
help |
-Prints a list of supported adb commands. | -- | |
version |
-Prints the adb version number. | -- | |
| Debug | -logcat [<option>] [<filter-specs>] |
-Prints log data to the screen. | -- |
bugreport |
-Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting. |
-- | |
jdwp |
-Prints a list of available JDWP processes on a given device. | -You can use the forward jdwp:<pid> port-forwarding specification to connect to a specific JDWP process. For example: - adb forward tcp:8000 jdwp:472- jdb -attach localhost:8000
- |
-|
| Data | -install <path-to-apk> |
-Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device. | -- |
pull <remote> <local> |
-Copies a specified file from an emulator/device instance to your development computer. | -- | |
push <local> <remote> |
-Copies a specified file from your development computer to an emulator/device instance. | -- | |
| Ports and Networking | -forward <local> <remote> |
-Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance. | -Port specifications can use these schemes:
-
|
-
ppp <tty> [parm]... |
-Run PPP over USB.
-
Note that you should not automatically start a PDP connection. |
-- | |
| Scripting | -get-serialno |
-Prints the adb instance serial number string. | -See Querying for Emulator/Device Instances for more information. | -
get-state |
-Prints the adb state of an emulator/device instance. | - -||
wait-for-device |
-Blocks execution until the device is online — that is, until the instance state is device. |
-You can prepend this command to other adb commands, in which case adb will wait until the emulator/device instance is connected before issuing the other commands. Here's an example:
-adb wait-for-device shell getprop- -Note that this command does not cause adb to wait until the entire system is fully booted. For that reason, you should not prepend it to other commands that require a fully booted system. As an example, the install requires the Android package manager, which is available only after the system is fully booted. A command such as
-
-adb wait-for-device install <app>.apk- -would issue the install command as soon as the emulator or device instance connected to the adb server, but before the Android system was fully booted, so it would result in an error. |
-|
| Server | -start-server |
-Checks whether the adb server process is running and starts it, if not. | -- |
kill-server |
-Terminates the adb server process. | -- | |
| Shell | -shell |
-Starts a remote shell in the target emulator/device instance. | -See Issuing Shell Commands for more information. | -
shell [<shellCommand>] |
-Issues a shell command in the target emulator/device instance and then exits the remote shell. | -
Adb provides an ash shell that you can use to run a variety of commands on an emulator -or device. The command binaries are stored in the file system of the emulator or device, -in this location:
- -/system/bin/...- -
You can use the shell command to issue commands, with or without entering the adb remote shell on the emulator/device.
To issue a single command without entering a remote shell, use the shell command like this:
adb [-d|-e|-s {<serialNumber>}] shell <shellCommand>
-
-To drop into a remote shell on a emulator/device instance, use the shell command like this:
adb [-d|-e|-s {<serialNumber>}] shell
-
-When you are ready to exit the remote shell, use CTRL+D or exit to end the shell session.
The sections below provide more information about shell commands that you can use.
- - - -From an adb remote shell, you can use the
-sqlite3 command-line program to
-manage SQLite databases created by Android applications. The
-sqlite3 tool includes many useful commands, such as
-.dump to print out the contents of a table and
-.schema to print the SQL CREATE statement for an existing table.
-The tool also gives you the ability to execute SQLite commands on the fly.
To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data/<package_name>/databases/.
Here's an example:
- -$ adb -s emulator-5554 shell -# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db -SQLite version 3.3.12 -Enter ".help" for instructions -.... enter commands, then quit... -sqlite> .exit- -
Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, use exit or CTRL+D.
-
-
-
-
-
The Monkey is a program that runs on your emulator or device and generates pseudo-random -streams of user events such as clicks, touches, or gestures, as well as a number of system-level -events. You can use the Monkey to stress-test applications that you are developing, -in a random yet repeatable manner.
- -The simplest way to use the monkey is with the following command, which will launch your -application and send 500 pseudo-random events to it.
- -$ adb shell monkey -v -p your.package.name 500- -
For more information about command options for Monkey, see the complete -UI/Application Exerciser Monkey documentation page.
- - - - -The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the adb -help command.
adb shell ls /system/bin- -
Help is available for most of the commands.
- -| Shell Command | -Description | -Comments | -
|---|---|---|
dumpsys |
-Dumps system data to the screen. | -The Dalvik Debug Monitor Service (DDMS) tool offers integrated debug environment that you may find easier to use. | -
dumpstate |
-Dumps state to a file. | -|
logcat [<option>]... [<filter-spec>]... |
-Enables radio logging and prints output to the screen. | -|
dmesg |
-Prints kernel debugging messages to the screen. | -|
start |
-Starts (restarts) an emulator/device instance. | -- |
stop |
-Stops execution of an emulator/device instance. | -- |
The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various applications and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command.
You can use the logcat command to view and follow the contents of the system's log buffers. The general usage is:
[adb] logcat [<option>] ... [<filter-spec>] ...- -
The sections below explain filter specifications and the command options. See Listing of logcat Command Options for a summary of options.
- -You can use the logcat command from your development computer or from a remote adb shell in an emulator/device instance. To view log output in your development computer, you use
$ adb logcat- -
and from a remote adb shell you use
- -# logcat- - - -
Every Android log message has a tag and a priority associated with it.
- -V — Verbose (lowest priority)D — DebugI — InfoW — WarningE — ErrorF — FatalS — Silent (highest priority, on which nothing is ever printed)You can obtain a list of tags used in the system, together with priorities, by running logcat and observing the first two columns
-of each message, given as <priority>/<tag>.
Here's an example of logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":
- -I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...}
-
-To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.
- -A filter expression follows this format tag:priority ..., where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single filter expression. The series of specifications is whitespace-delimited.
Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:
- -adb logcat ActivityManager:I MyApp:D *:S- -
The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a "whitelist" for log output.
The following filter expression displays all log messages with priority level "warning" and higher, on all tags:
- -adb logcat *:W- -
If you're running logcat from your development computer (versus running it on a remote adb shell), you can also set a default filter expression by exporting a value for the environment variable ANDROID_LOG_TAGS:
export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"- -
Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device instance, if you are running logcat from a remote shell or using adb shell logcat.
Log messages contain a number of metadata fields, in addition to the tag and priority. You can modify the output format for messages so that they display a specific metadata field. To do so, you use the -v option and specify one of the supported output formats listed below.
brief — Display priority/tag and PID of originating process (the default format).process — Display PID only.tag — Display the priority/tag only. thread — Display process:thread and priority/tag only. raw — Display the raw log message, with no other metadata fields.time — Display the date, invocation time, priority/tag, and PID of the originating process.long — Display all metadata fields and separate messages with a blank lines.When starting logcat, you can specify the output format you want by using the -v option:
[adb] logcat [-v <format>]- -
Here's an example that shows how to generate messages in thread output format:
adb logcat -v thread- -
Note that you can only specify one output format with the -v option.
The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can start logcat with the -b option, to request viewing of an alternate circular buffer. You can view any of these alternate buffers:
radio — View the buffer that contains radio/telephony related messages.events — View the buffer containing events-related messages.main — View the main log buffer (default)The usage of the -b option is:
[adb] logcat [-b <buffer>]- -
Here's an example of how to view a log buffer containing radio and telephony messages:
- -adb logcat -b radio- - - -
By default, the Android system sends stdout and stderr (System.out and System.err) output to /dev/null. In
-processes that run the Dalvik VM, you can have the system write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr, both with priority I.
To route the output in this way, you stop a running emulator/device instance and then use the shell command setprop to enable the redirection of output. Here's how you do it:
$ adb shell stop -$ adb shell setprop log.redirect-stdio true -$ adb shell start- -
The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop
-on the device.
| Option | -Description | -
|---|---|
-b <buffer> |
-Loads an alternate log buffer for viewing, such as event or radio. The main buffer is used by default. See Viewing Alternative Log Buffers. |
-
-c |
-Clears (flushes) the entire log and exits. | -
-d |
-Dumps the log to the screen and exits. | -
-f <filename> |
-Writes log message output to <filename>. The default is stdout. |
-
-g |
-Prints the size of the specified log buffer and exits. | -
-n <count> |
-Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option. |
-
-r <kbytes> |
-Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option. |
-
-s |
-Sets the default filter spec to silent. | -
-v <format> |
-Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format. |
-
In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem.
- -To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command.
The Android Development Tools (ADT) plugin adds powerful extensions to the Eclipse integrated development environment. It allows you to create and debug your Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications:
- -If you will not be using the Eclipse IDE, you do not need to download or install the ADT plugin.
- -To download and install the ADT plugin, follow the steps below for your respective Eclipse version.
- -| Eclipse 3.3 (Europa) | Eclipse 3.4 (Ganymede) |
|---|---|
-
|
-
-
-
|
-
-If you are having trouble downloading the ADT plugin after following the steps above, here are some suggestions:
- -http, rather than https. -If you are still unable to use Eclipse to download the ADT plugin, follow these steps to download and install the plugin from your computer: -
--Note that to update your plugin, you will have to follow these steps again instead of the default update instructions.
- -Note that the "Android Editors" feature of ADT requires several optional -Eclipse components (for example, WST). If you encounter an error when -installing ADT, your Eclipse installion might not include those components. -For information about how to quickly add the necessary components to your -Eclipse installation, see the troubleshooting topic -ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".
- -If you encounter this error when installing the ADT Plugin for Eclipse: -
-An error occurred during provisioning. -Cannot connect to keystore. -JKS-
-...then your development machine lacks a suitable Java VM. Installing Sun -Java 6 will resolve this issue and you can then reinstall the ADT -Plugin.
- - - -In some cases, a new ADT plugin may become available for your existing version of the SDK. You can use the steps below to update -the ADT plugin from inside Eclipse.
- -| Eclipse 3.3 (Europa) | Eclipse 3.4 (Ganymede) |
|---|---|
-
Alternatively, -
|
-
-
|
-
Since each application runs in its own process, and you can write a service that -runs in a different process from your Application's UI, sometimes you need to pass objects -between processes. On the Android platform, one process can not normally access the memory -of another process. So to talk, they need to decompose their objects into primitives that -the operating system can understand, and "marshall" the object across that boundary for you.
- -The code to do that marshalling is tedious to write, so we provide the AIDL tool to do it -for you.
- -AIDL (Android Interface Definition Language) is an IDL -language used to generate code that enables two processes on an Android-powered device -to talk using interprocess communication (IPC). If you have code -in one process (for example, in an Activity) that needs to call methods on an -object in another process (for example, a Service), you would use AIDL to -generate code to marshall the parameters.
-The AIDL IPC mechanism - is interface-based, similar to COM or Corba, but lighter weight. It uses a proxy - class to pass values between the client and the implementation.
-This page includes the following main topics:
- -Follow these steps to implement an IPC service using AIDL.
-tools/ directory. AIDL is a simple syntax that lets you declare an interface with one or more - methods, that can take parameters and return values. These parameters and return - values can be of any type, even other AIDL-generated interfaces. However, it - is important to note that you must import all non-built-in types, - even if they are defined in the same package as your interface. - Here are the data types that AIDL can support:
-import statement is needed. import statements needed):
- import statement is always needed for these.import statement is always needed for these.Here is the basic AIDL syntax:
-// My AIDL file, named SomeClass.aidl
-// Note that standard comment syntax is respected.
-// Comments before the import or package statements are not bubbled up
-// to the generated interface, but comments above interface/method/field
-// declarations are added to the generated interface.
-
-// Include your fully-qualified package statement.
-package com.android.sample;
-
-// See the list above for which classes need
-// import statements (hint--most of them)
-import com.android.sample.IAtmService;
-
-// Declare the interface.
-interface IBankAccountService {
-
- // Methods can take 0 or more parameters, and
- // return a value or void.
- int getAccountBalance();
- void setOwnerNames(in List<String> names);
-
- // Methods can even take other AIDL-defined parameters.
- BankAccount createAccount(in String name, int startingDeposit, in IAtmService atmService);
-
- // All non-Java primitive parameters (e.g., int, bool, etc) require
- // a directional tag indicating which way the data will go. Available
- // values are in, out, inout. (Primitives are in by default, and cannot be otherwise).
- // Limit the direction to what is truly needed, because marshalling parameters
- // is expensive.
- int getCustomerList(in String branch, out String[] customerList);
-}
-
-AIDL generates an interface file for you with the same name as your .aidl - file. If you are using the Eclipse plugin, AIDL will automatically be run as part of - the build process (you don't need to run AIDL first and then build your project). - If you are not using the plugin, you should run AIDL first.
-The generated interface - includes an abstract inner class named Stub that declares all the methods - that you declared in your .aidl file. Stub also defines a few helper methods, - most notably asInterface(), which takes an IBinder (passed to a client's onServiceConnected() - implementation when applicationContext.bindService() succeeds), and returns an - instance of the interface used to call the IPC methods. See the section - Calling an IPC Method for more details on how to make this cast.
-To implement your interface, extend YourInterface.Stub, - and implement the methods. (You can create the .aidl file and implement the stub - methods without building between--the Android build process will process .aidl -files before .java files.)
-Here is an example of implementing an interface called IRemoteService, which exposes - a single method, getPid(), using an anonymous instance:
-// No need to import IRemoteService if it's in the same project.
-private final IRemoteService.Stub mBinder = new IRemoteService.Stub(){
- public int getPid(){
- return Process.myPid();
- }
-}
-A few rules about implementing your interface:
-Now that you've got your interface implementation, you need to expose it to clients. - This is known as "publishing your service." To publish a service, - inherit {@link android.app.Service Service} and implement {@link android.app.Service#onBind - Service.onBind(Intent)} to return an instance of the class that implements your interface. - Here's a code snippet of a service that exposes the IRemoteService - interface to clients.
-public class RemoteService extends Service {
-...
-{@include development/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java
- exposing_a_service}
-}
-
-
-If you have a class that you would like to send from one process to another through -an AIDL interface, you can do that. You must ensure that the code for your class is available -to the other side of the IPC. Generally, that means that you're talking to a service that you -started.
-There are five parts to making a class support the Parcelable protocol: -
public void writeToParcel(Parcel out) that takes the
-current state of the object and writes it to a parcel.public void readFromParcel(Parcel in) that reads the
-value in a parcel into your object.CREATOR to your class which is an object implementing
-the {@link android.os.Parcelable.Creator Parcelable.Creator} interface.AIDL will use these methods and fields in the code it generates to marshall and unmarshall -your objects.
-Here is an example of how the {@link android.graphics.Rect} class implements the -Parcelable protocol.
- -
-import android.os.Parcel;
-import android.os.Parcelable;
-
-public final class Rect implements Parcelable {
- public int left;
- public int top;
- public int right;
- public int bottom;
-
- public static final Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect>() {
- public Rect createFromParcel(Parcel in) {
- return new Rect(in);
- }
-
- public Rect[] newArray(int size) {
- return new Rect[size];
- }
- };
-
- public Rect() {
- }
-
- private Rect(Parcel in) {
- readFromParcel(in);
- }
-
- public void writeToParcel(Parcel out) {
- out.writeInt(left);
- out.writeInt(top);
- out.writeInt(right);
- out.writeInt(bottom);
- }
-
- public void readFromParcel(Parcel in) {
- left = in.readInt();
- top = in.readInt();
- right = in.readInt();
- bottom = in.readInt();
- }
-}
-
-
-Here is Rect.aidl for this example
- --package android.graphics; - -// Declare Rect so AIDL can find it and knows that it implements -// the parcelable protocol. -parcelable Rect; -- -
The marshalling in the Rect class is pretty simple. Take a look at the other -methods on {@link android.os.Parcel} to see the other kinds of values you can write -to a Parcel.
- -Warning: Don't forget the security implications of receiving data from -other processes. In this case, the rect will read four numbers from the parcel, -but it is up to you to ensure that these are within the acceptable range of -values for whatever the caller is trying to do. See -Security and Permissions for more -on how to keep your application secure from malware.
- -Here are the steps a calling class should make to call your remote interface:
-YourInterfaceName.Stub.asInterface((IBinder)service) to
- cast the returned parameter to YourInterface type.A few comments on calling an IPC service:
-Here is some sample code demonstrating calling an AIDL-created service, taken - from the Remote Activity sample in the ApiDemos project.
-{@sample development/samples/ApiDemos/src/com/example/android/apis/app/RemoteServiceBinding.java - exposing_a_service}
- - - diff --git a/docs/html/guide/developing/tools/ddms.jd b/docs/html/guide/developing/tools/ddms.jd deleted file mode 100644 index fa04216..0000000 --- a/docs/html/guide/developing/tools/ddms.jd +++ /dev/null @@ -1,250 +0,0 @@ -page.title=Using Dalvik Debug Monitor Service (DDMS) -@jd:body - -Android ships with a debugging tool called the Dalvik Debug Monitor Service (DDMS), - which provides port-forwarding services, screen capture on the device, thread - and heap information on the device, logcat, process, and radio state information, - incoming call and SMS spoofing, location data spoofing, and more. This page - provides a modest discussion of DDMS features; it is not an exhaustive exploration of - all the features and capabilities.
- -DDMS ships in the tools/ directory of the SDK.
- Enter this directory from a terminal/console and type ddms (or ./ddms
- on Mac/Linux) to run it. DDMS will work with both the emulator and a connected device. If both are
- connected and running simultaneously, DDMS defaults to the emulator.
DDMS acts as a middleman to connect the IDE to the applications running on -the device. On Android, every application runs in its own process, -each of which hosts its own virtual machine (VM). And each process -listens for a debugger on a different port.
- -When it starts, DDMS connects to adb and -starts a device monitoring service between the two, which will notify DDMS when a device is -connected or disconnected. When a device is connected, a VM monitoring service is created -between adb and DDMS, which will notify DDMS when a VM on the device is started -or terminated. Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb, -and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. -DDMS can now talk to the VM using a custom wire protocol.
- -For each VM on the device, DDMS opens a port upon which it will listen for a debugger. For the first VM, DDMS listens for a debugger on port 8600, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded between the debugger and the associated VM. Debugging can then process like any remote debugging session.
- -DDMS also opens another local port, the DDMS "base port" (8700, by default), upon which it also listens for a debugger. When a debugger connects to this base port, all traffic is forwarded to the VM currently selected in DDMS, so this is typically where you debugger should connect.
- -For more information on port-forwarding with DDMS, -read Configuring your IDE to attach -to port 8700 for debugging.
- -Tip: -You can set a number of DDMS preferences in File > Preferences. -Preferences are saved to "$HOME/.ddmsrc".
- -Known debugging issues with Dalvik
-Debugging an application in the Dalvik VM should work the same as it does
-in other VMs. However, when single-stepping out of synchronized code, the "current line"
-cursor may jump to the last line in the method for one step.
The left side of the Debug Monitor shows each emulator/device currently found, with a list of - all the VMs currently running within each. - VMs are identified by the package name of the application it hosts.
-Use this list to find and attach to the VM - running the activity(ies) that you want to debug. Next to each VM in the - list is a "debugger pass-through" port (in the right-most column). - If you connect your debugger to one of the the ports listed, you - will be connected to the corresponding VM on the device. However, when using - DDMS, you need only connect to port 8700, as DDMS forwards all traffic here to the - currently selected VM. (Notice, as you select a VM in the list, the listed port includes 8700.) - This way, there's no need to reconfigure the debugger's port each time you switch between VMs.
-When an application running on the device calls {@link android.os.Debug#waitForDebugger()} - (or you select this option in the developer - options), a red icon will be shown next to the client name, while it waits for the - debugger to attach to the VM. When a debugger is connected, the icon will turn green.
-If you see a crossed-out bug icon, this means that the DDMS was unable to complete a -connection between the debugger and the VM because it was unable to open the VM's local port. -If you see this for all VMs on the device, it is likely because you have another instance of -DDMS running (this includes the Eclipse plugin).
-If you see a question mark in place of an application package, this means that, -once DDMS received the application pid from adb, it -somehow failed to make a successful handshake with the VM process. Try restarting DDMS.
- - -On the right side, the Debug Monitor provides tabs that display useful information -and some pretty cool tools.
- -This view shows some general information about the selected VM, including the process - ID, package name, and VM version.
- -The threads view has a list of threads running in the process of the target VM. - To reduce the amount - of data sent over the wire, the thread updates are only sent when explicitly - enabled by toggling the "threads" button - in the toolbar. This toggle is maintained per VM. This tab includes the following - information:
-"ID" and "Name" are set when the thread is started. The remaining - fields are updated periodically (default is every 4 seconds).
- -Displays some heap stats, updated during garbage collection. If, when a VM is selected, -the VM Heap view says that heap updates are not enabled, click the "Show heap updates" button, -located in the top-left toolbar. Back in the VM Heap view, click Cause GC -to perform garbage collection and update the heap stats.
- - -In this view, you can track the memory allocation of each virtual machine. -With a VM selected in the left pane, click Start Tracking, then -Get Allocations to view all allocations since tracking started. -The table below will be filled with all the relevant -data. Click it again to refresh the list.
- - -With these controls, you can simulate special device states and activities. -Features include:
-To use the Location Controls, launch your application in the Android emulator and open DDMS. -Click the Emulator Controls tab and scroll down to Location Controls. -From here, you can:
-Click Manual, - select the coordinate format, fill in the fields and click Send. -
-Click GPX and load the file. Once loaded, - click the play button to playback the route for your location-aware application.
-When performing playback from GPX, you can adjust the speed of
- playback from the DDMS panel and control playback with the pause and skip buttons.
- DDMS will parse both the waypoints (<wpt>, in the first table),
- and the tracks (<trk>,
- in the second table, with support for multiple segments, <trkseg>,
- although they are simply
- concatenated). Only the tracks can be played. Clicking a waypoint in the first list simply
- sends its coordinate to the device, while selecting a track lets you play it.
Click KML and load the file. Once loaded, - click the play button to send the coordinates to your location-aware application.
-When using a KML file, it is parsed for a <coordinates>
- element. The value of which should be a single
- set of longitude, latitude and altitude figures. For example:
<coordinates>-122.084143,37.421972,4</coordinates>-
In your file, you may include multiple <Placemark> elements, each containing
- a <coordinates> element. When you do so, the collection of placemarks will
- be added as tracks. DDMS will send one placemark per second to the device.
One way to generate a suitable KML file is to find a location in Google Earth. - Right-click the location entry that appears on the left and select "Save place as..." - with the save format set to Kml.
-Note: DDMS does not support routes created with the
-<MultiGeometry><LineString>lat1, long1, lat2, long2, ....</LineString></MultiGeometry> methods.
- There is also currently no support for the <TimeStamp> node inside
- the <Placemark>.
- Future releases may support timed placement and routes within a single coordinate element.
For additional methods of setting up mocks of location-based data, see the - Location topic.
-With the File Explorer, you can view the device file system and perform basic management,
-like pushing and pulling files. This circumvents using the adb
-push and pull commands, with a GUI experience.
With DDMS open, select Device > File Explorer... to open the -File Explorer window. You can drag-and-drop into the device directories, but cannot drag out of them. -To copy files from the device, select the file and click the Pull File from Device -button in the toolbar. To delete files, use the Delete button in the toolbar.
-If you're interested in using an SD card image on the emulator, you're still required to use
-the mksdcard command to create an image, and then mount it during emulator bootup.
-For example, from the /tools directory, execute:
-$ mksdcard 1024M ./img -$ emulator -sdcard ./img --
Now, when the emulator is running, the DDMS File Explorer will be able to read and write to the -sdcard directory. However, your files may not appear automatically. For example, if you add an -MP3 file to the sdcard, the media player won't see them until you restart the emulator. (When restarting -the emulator from command line, be sure to mount the sdcard again.)
-For more information on creating an SD card image, see the -Other Tools document.
- -You can capture screen images on the device or emulator by selecting Device - > Screen capture... in the menu bar, or press CTRL-S.
- -You can see the output of ps -x for a specific VM by selecting Device
- > Show process status... in the menu bar.
Cause garbage collection to occury by pressing the trash can button on the toolbar.
- -By default, radio state is not output during a standard logcat (it is a lot of - information). To see radio information, either click Device > Dump radio - state... or run logcat as described in Logging - Radio Information.
- -You can stop a virtual machine by selecting Actions > Halt
-VM. Pressing this button causes the VM to call System.exit(1).
DDMS has the following known limitations:
-The Draw 9-patch tool allows you to easily create a - {@link android.graphics.NinePatch} graphic using a WYSIWYG editor.
-For an introduction to Nine-patch graphics and how they work, please read -the section on Nine-patch in the -Ninepatch Images topic.
- -
-Here's a quick guide to create a Nine-patch graphic using the Draw 9-patch tool. -You'll need the PNG image with which you'd like to create a NinePatch.
- -draw9patch application from your SDK
- /tools directory.
- The left pane is your drawing area, in which you can edit the lines for the - stretchable patches and content area. The right - pane is the preview area, where you can preview your graphic when stretched.
-Your image will be saved with the .9.png file name.
Note: A normal PNG file (*.png) will be
- loaded with an empty one-pixel border added around the image, in which you can draw
- the stretchable patches and content area.
- A previously saved 9-patch file (*.9.png) will be loaded as-is,
- with no drawing area added, because it already exists.
-Optional controls include:
-
-
-The Android SDK includes a mobile device emulator -- a virtual mobile device -that runs on your computer. The emulator lets you prototype, develop, and test -Android applications without using a physical device.
- -The Android emulator mimics all of the typical hardware and software features -of a typical mobile device, except that it can not receive or place actual phone -calls. It provides a variety of navigation and control keys, which you can "press" -using your mouse or keyboard to generate events for your application. It also -provides a screen in which your application is displayed, together with any other -Android applications running.
- -To help you model and test your application, the emulator lets your application -use the services of the Android platform to invoke other applications, access the -network, play audio and video, store and retrieve data, notify the user, and render -graphical transitions and themes.
- -The emulator also includes a variety of debug capabilities, such as a console -from which you can log kernel output, simulate application interrupts (such as -arriving SMS messages or phone calls), and simulate latency effects and dropouts -on the data channel.
- - - - -The Android emulator is a QEMU-based application that provides a virtual ARM -mobile device on which you can run your Android applications. It provides a full -Android system stack, down to the kernel level, and includes a set of -preinstalled applications (such as the dialer) that you can access from your -applications. It provides a skinnable mobile device UI, customizable key -mappings, and a variety of commands and options for controlling the behaviors of -the emulated environment.
- -The Android system image distributed in the SDK contains ARM machine code for -the Android Linux kernel, the native libraries, the Dalvik VM, and the various -Android package files (such as for for the Android framework and preinstalled -applications). The emulator's QEMU layers provide dynamic binary translation of -the ARM machine code to the OS and processor architecture of your development -machine.
- -Adding custom capabilities to the underlying QEMU services, the Android -emulator supports many hardware features likely to be found on mobile devices, -including:
- -The sections below provide more information about the emulator and how to use -it for developing Android applications.
- - - -During development and testing of your application, you install and run your -application in the Android emulator. You can launch the emulator as a standalone -application, from a command line, or you can use it as part of your Eclipse -development environment. In either case, you can specify the startup options -described in this document to control the emulator. -
- -You can run your application on a single instance of the emulator or, -depending on your needs, you can start multiple emulator instances and run your -application in more than one emulated device. You can use the emulator's -built-in commands to simulate GSM phone calling or SMS between emulator -instances, and you can set up network redirections that allow emulators to send -data to one another. For more information, see Telephony -Emulation, SMS Emulation, and -Emulator Networking
- -To start an instance of the emulator from the command line, change to the
-tools/ folder of the SDK and enter emulator or
-./emulator. This initializes the Android system and you will see
-the emulator window appear on your screen.
If you are working in Eclipse, the ADT plugin for Eclipse installs your -application and starts the emulator automatically, when you run or debug -the application. You can specify emulator startup options in the Run/Debug -dialog, in the Target tab. When the emulator is running, you can issue -console commands as described later in this document.
- -If you are not working in Eclipse, see Installing Applications -on the Emulator for information about how to install your application.
- -To stop an emulator instance, just close the emulator's window.
- - - -You can use emulator startup options and console commands to control the behaviors and -characteristics of the emulated environment itself. -
- -When the emulator is running, you can interact with the emulated mobile -device just as you would an actual mobile device, except that you use your mouse -pointer to "touch" the touchscreen and your keyboard keys to -"press" the simulated device keys.
- -The table below summarizes the mappings between the emulator keys and and -the keys of your keyboard.
- -| Emulated Device Key | -Keyboard Key | -
|---|---|
| Home | -HOME | -
| Menu (left softkey) | -F2 or Page-up button | -
| Star (right softkey) | -Shift-F2 or Page Down | -
| Back | -ESC | -
| Call/dial button | -F3 | -
| Hangup/end call button | -F4 | -
| Search | -F5 | -
| Power button | -F7 | -
| Audio volume up button | -KEYPAD_PLUS, Ctrl-5 | -
| Audio volume down button | -KEYPAD_MINUS, Ctrl-F6 | -
| Camera button | -Ctrl-KEYPAD_5, Ctrl-F3 | -
| Switch to previous layout orientation (for example, portrait, landscape) | -KEYPAD_7, F11 | -
| Switch to next layout orientation (for example, portrait, landscape) | -KEYPAD_9, F12 | -
| Toggle cell networking on/off | -F8 | -
| Toggle code profiling | -F9 (only with -trace startup option) |
-
| Toggle fullscreen mode | -Alt-Enter | -
| Toggle trackball mode | -F6 | -
| Enter trackball mode temporarily (while key is pressed) | -Delete | -
| DPad left/up/right/down | -KEYPAD_4/8/6/2 | -
| DPad center click | -KEYPAD_5 | -
| Onion alpha increase/decrease | -KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/) | -
Note that, to use keypad keys, you must first disable NumLock on your development computer.
- - - -The emulator supports a variety of options that you can specify -when launching the emulator, to control its appearance or behavior. -Here's the command-line usage for launching the emulator with options:
- -emulator [-<option> [<value>]] ... [-<qemu args>]- -
The table below summarizes the available options.
- -| Category | -Option | -Description | -Comments | -
|---|---|---|---|
| Help | --help |
- Print a list of all emulator options. | -- |
-help-all |
- Print help for all startup options. | -- | |
-help-<option> |
- Print help for a specific startup option. | -- | |
-help-debug-tags |
- Print a list of all tags for -debug <tags>. |
- - | |
-help-disk-images |
- Print help for using emulator disk images. | -- | |
-help-environment |
- Print help for emulator environment variables. | -- | |
-help-keys |
- Print the current mapping of keys. | -- | |
-help-keyset-file |
- Print help for defining a custom key mappings file. | -- | |
| Disk Images | --cache <filepath> |
- Use <filepath> as the working cache partition image. | -Optionally, you can specify a path relative to the current working directory.
- If no cache file is specified, the emulator's default behavior is to use a temporary file instead.
- For more information on disk images, use |
-data <filepath> |
- Use <filepath> as the working user-data disk image. | -Optionally, you can specify a path relative to the current working directory.
- If -data is not used, the emulator looks for a file named "userdata-qemu.img"
- in the directory specified in <datadir>. ~/.android/SDK-1.0 (on Linux/Mac) or
- C:\Documents and Settings\<user>\Local Settings\Application Data\Android\SDK-1.0 (on Windows).
- If you use See Running Multiple Emulator Instances for information about how
- to use For more information on disk images, use | |
-image <filepath> |
- Use <filepath> as the system image. | -Optionally, you can specify a path relative to the current working directory. - Default is <system>/system.img. | -|
-initdata <filepath> |
- When resetting the user-data image (through -wipe-data), copy the contents
- of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img. |
- Optionally, you can specify a path relative to the current working directory. See also -wipe-data. For more information on disk images, use |
-|
-kernel <filepath> |
- Use <filepath> as the emulated kernel. | -Optionally, you can specify a path relative to the current working directory. | -|
-nocache |
- Start the emulator without a cache partition. | -See also -cache <file>. |
-|
-ramdisk <filepath> |
- Use <filepath> as the ramdisk image. | -Default value is <system>/ramdisk.img.
- Optionally, you can specify a path relative to the current working directory. For more information on disk images, use |
-|
-sdcard <filepath> |
- Use <file> as the SD card image. | -Default value is <system>/sdcard.img.
- Optionally, you can specify a path relative to the current working directory. For more information on disk images, use |
-|
-system <dirpath> |
- Search for system, ramdisk and user data images in <dir>. | -<dir> is a directory path relative to the current
- working directory. |
-|
-wipe-data |
- Reset the current user-data disk image (that is, the file specified by -datadir and
- -data, or the default file). The emulator deletes all data from the user data image file,
- then copies the contents of the file at -inidata data to the image file before starting.
- |
- See also -initdata.
- For more information on disk images, use |
-|
| Debug | --debug <tags> |
- Enable/disable debug messages for the specified debug tags. | -<tags> is a space/comma/column-separated list of debug component names.
- Use -help-debug-tags to print a list of debug component names that you can use. |
-
-debug-<tag> |
- Enable/disable debug messages for the specified debug tag. | -Use -help-debug-tags to print a list of debug component names that you can use in <tag>. |
-|
-debug-no-<tag> |
- Disable debug messages for the specified debug tag. | -||
-logcat <logtags> |
- Enable logcat output with given tags. | -If the environment variable ANDROID_LOG_TAGS is defined and not - empty, its value will be used to enable logcat output by default. | -|
-shell |
- Create a root shell console on the current terminal. | -You can use this command even if the adb daemon in the emulated system is broken. - Pressing Ctrl-c from the shell stops the emulator instead of the shell. | -|
-shell-serial <device> |
- Enable the root shell (as in -shell and specify the QEMU character
- device to use for communication with the shell. |
- <device> must be a QEMU device type. See the documentation for 'serial -dev' at
- http://www.bellard.org/qemu/qemu-doc.html#SEC10
- for a list of device types.
-
- Here are some examples: -
|
-|
-show-kernel <name> |
- Display kernel messages. | -- | |
-trace <name> |
- Enable code profiling (press F9 to start), written to a specified file. | -- | |
-verbose |
- Enable verbose output. | -Equivalent to -debug-init.
-You can define the default verbose output options used by emulator instances in the Android environment variable
-ANDROID_VERBOSE. Define the options you want to use in a comma-delimited list, specifying only the stem of each option:
- Here's an example showing ANDROID_VERBOSE defined with the
For more information about debug tags, use |
-|
| Media | --audio <backend> |
- Use the specified audio backend. | -- |
-audio-in <backend> |
- Use the specified audio-input backend. | -- | |
-audio-out <backend> |
- Use the specified audio-output backend. | -- | |
-noaudio |
- Disable audio support in the current emulator instance. | -- | |
-radio <device> |
- Redirect radio modem interface to a host character device. | -||
-useaudio |
- Enable audio support in the current emulator instance. | -Enabled by default. | -|
| Network | --dns-server <servers> |
- Use the specified DNS server(s). | -The value of <servers> must be a comma-separated list of up to 4 DNS server names or
- IP addresses. |
-
-http-proxy <proxy> |
- Make all TCP connections through a specified HTTP/HTTPS proxy | -The value of <proxy> can be one of the following:- http://<server>:<port>- http://<username>:<password>@<server>:<port>
- The |
-|
-netdelay <delay> |
- Set network latency emulation to <delay>. | -Default value is none. See the table in Network Delay Emulation for
- supported <delay> values. |
-|
-netfast |
- Shortcut for -netspeed full -netdelay none |
- ||
-netspeed <speed> |
- Set network speed emulation to <speed>. | -Default value is full. See the table in Network Speed Emulation for
- supported <speed> values. |
-|
-port <port> |
- Set the console port number for this emulator instance to <port>. |
- The console port number must be an even integer between 5554 and 5584, inclusive. <port>+1
- must also be free and will be reserved for ADB. |
-|
-report-console <socket> |
- Report the assigned console port for this emulator instance to a remote third party - before starting the emulation. | -<socket> must use one of these formats:
-
-
Use |
-|
| System | --cpu-delay <delay> |
- Slow down emulated CPU speed by <delay> | -Supported values for <delay> are integers between 0 and 1000.
-
- Note that the <delay> does not correlate to clock speed or other absolute metrics -— it simply represents an abstract, relative delay factor applied non-deterministically -in the emulator. Effective performance does not always -scale in direct relationship with <delay> values. - |
-
-gps <device> |
- Redirect NMEA GPS to character device. | -Use this command to emulate an NMEA-compatible GPS unit connected to
- an external character device or socket. The format of <device> must be QEMU-specific
- serial device specification. See the documentation for 'serial -dev' at
- http://www.bellard.org/qemu/qemu-doc.html#SEC10.
- |
-|
-nojni |
- Disable JNI checks in the Dalvik runtime. | ||
-qemu |
- Pass arguments to qemu. | -||
-qemu -h |
- Display qemu help. | -||
-radio <device> |
- Redirect radio mode to the specified character device. | -The format of <device> must be QEMU-specific
- serial device specification. See the documentation for 'serial -dev' at
-http://www.bellard.org/qemu/qemu-doc.html#SEC10.
- |
-|
-timezone <timezone> |
- Set the timezone for the emulated device to <timezone>, instead of the host's timezone. | -<timezone> must be specified in zoneinfo format. For example:
-"America/Los_Angeles" |
-|
-version |
- Display the emulator's version number. | -- | |
| UI | --dpi-device <dpi> |
- Scale the resolution of the emulator to match the screen size - of a physical device. | -The default value is 165. See also -scale. |
-
-no-boot-anim |
- Disable the boot animation during emulator startup. | -Disabling the boot animation can speed the startup time for the emulator. | -|
-no-window |
- Disable the emulator's graphical window display. | -- | |
-scale <scale> |
- Scale the emulator window. | -<scale> is a number between 0.1 and 3 that represents the desired scaling factor. You can
- also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto"
- tells the emulator to select the best window size. |
-|
-raw-keys |
- Disable Unicode keyboard reverse-mapping. | -||
-noskin |
- Don't use any emulator skin. | -||
-keyset <file> |
- Use the specified keyset file instead of the default. | -The keyset file defines the list of key bindings between the emulator and the host keyboard.
- For more information, use -help-keyset to print information about this topic.
- |
-|
-onion <image> |
- Use overlay image over screen. | -No support for JPEG. Only PNG is supported. | |
-onion-alpha <percent> |
- Specify onion skin translucency value (as percent). - | Default is 50. | -|
-onion-rotation <position> |
- Specify onion skin rotation. - | <position> must be one of the values 0, 1, 2, 3. |
-|
-skin <skinID> |
- Start the emulator with the specified skin. | -The SDK includes a choice of four skins: - |
-|
-skindir <dir> |
- Search for emulator skins in <dir>. | -
The emulator uses mountable disk images stored on your development machine to -simulate flash (or similar) partitions on an actual device. For example, it uses -disk image containing an emulator-specific kernel, the Android system, a -ramdisk image, and writeable images for user data and simulated SD card.
- -To run properly, the emulator requires access to a specific set of disk image -files. The Android SDK includes default versions of the required images, stored -in predetermined locations in the SDK directory structure. At startup, the -emulator looks for and reads the image files, using their default names and -storage locations.
- -To let you use alternate or custom versions of the image files, the emulator -provides startup options that override the default locations and filenames of -the image files. When you use the options, the emulator searches for the image -file under the image name or location that you specify; if it can not locate the -image, it reverts to using the default names and location.
- -The emulator uses three types of image files: system image files, runtime -image files, and temporary image files. The sections below describe how to -override the location/name of each type of file.
- - -System images contain system data and default settings without which the -emulator can not run. The image files are read-only — the emulator reads -the images at startup and does not modify them during the session.
- -All of the system image files are stored in a single directory. By default,
-the system images are stored in the lib/images' under the
-emulator's program location.
The emulator provides the -system <dir> startup option to
-let you override the location under which the emulator looks for the system
-images files.
The emulator also provides startup options that let you override the names of
-the system images, as described in the table below. When you use one of the
-options, the emulator looks in the default directory, or in a custom location
-(if you specified -system <dir>). Note that, if you provide
-alternate system image file, it must contain the same type of data as the
-default. For example, your override of the system.img file must point to a disk
-image containing an Android system.
| Name | -Description | -Comments | -
|---|---|---|
kernel-qemu.img |
- The emulator-specific Linux kernel image | -Override using -kernel <file> |
-
ramdisk.img |
- The ramdisk image used to boot the system. | -Override using -ramdisk <file> |
-
system.img |
- The initial Android system image. | -Override using -image <file> |
-
userdata.img |
- The initial user-data disk image | -Override using -initdata <file>. Also see
--data <file>, below. |
-
At runtime, the emulator reads and writes data on two disk images: a -user-data image and (optionally) an SD card image. This emulates the user-data -partition and removable storage media on actual device.
- -The emulator provides a default user-data disk image. At startup, the emulator -creates the default image as a copy of the system user-data image (user-data.img), -described above. The emulator stores the default image in this location on -on your development machine:
- -~/.android/SDK-1.0C:\Documents and Settings\<user>\Local Settings\Application Data\Android\SDK-1.0The emulator provides startup options to let you override the actual names and storage -locations of the runtime images to load, as described in the table below. When you use one -of these options, the emulator looks for the specified file(s) in the current working directory, -in the default directory, or in a custom location (if you specified a path with the filename.
- -| Name | -Description | -Comments | -
|---|---|---|
userdata-qemu.img |
- An image to which the emulator writes runtime user-data for a unique user. | -Override using -data <filepath>, where <filepath> is the
-path the image, relative to the current working directory. If you supply a filename only,
-the emulator looks for the file in the current working directory. If the file at <filepath> does
-not exist, the emulator creates an image from the default userdata.img, stores it under the name you
-specified, and persists user data to it at shutdown. |
-
sdcard.img |
- An image representing an SD card inserted into the emulated device. | -Override using -sdcard <filepath>, where <filepath> is the
-path the image, relative to the current working directory. If you supply a filename only,
-the emulator looks for the file in the current working directory. |
-
Each emulator instance uses a writeable user-data image to store user- and -session-specific data. For example, it uses the image to store a unique user's -installed application data, settings, databases, and files.
- -At startup, the emulator attempts to load a user-data image stored during -a previous session. It looks for the file in the current working directory, -at the default location, as described above, and at the custom location/name -that you specified at startup.
- --data startup option.If you are planning to run multiple emulator instances concurrently, note
-that only the first emulator instance can persist user-data, if no explicit
-user-data image file is specified in the startup command. When running multiple
-emulator instances, you must specify a name for the image file to use (or
-create), by using the -data <name> option with a unique
-<name> value. For more information, see
-Running Multiple Emulator Instances.
Optionally, you can create a writeable disk image that the emulator can use -to simulate removeable storage in an actual device. For information about how to create an -emulated SD card and load it in the emulator, see SD Card Emulation
- - -The emulator creates two writeable images at startup that it deletes at -device power-off. The images are:
- -/cache partition imageThe emulator does not permit renaming the temporary system image or -persisting it at device power-off.
- -The /cache partition image is initially empty, and is used by
-the browser to cache downloaded web pages and images. The emulator provides an
--cache <file>, which specifies the name of the file at which
-to persist the /cache image at device power-off. If <file>
- does not exist, the emulator creates it as an empty file.
You can also disable the use of the cache partition by specifying the
--nocache option at startup.
The emulator provides versatile networking capabilities that you can use to -set up complex modeling and testing environments for your application. The -sections below introduce the emulator's network architecture and capabilities. -
- - -Each instance of the emulator runs behind a virtual router/firewall service -that isolates it from your development machine's network interfaces and settings -and from the internet. An emulated device can not see your development machine -or other emulator instances on the network. Instead, it sees only that it is -connected through Ethernet to a router/firewall.
- -The virtual router for each instance manages the 10.0.2/24 network address -space — all addresses managed by the router are in the form of -10.0.2.<xx>, where <xx> is a number. Addresses within this space are -pre-allocated by the emulator/router as follows:
- -| Network Address | -Description | -
|---|---|
| 10.0.2.1 | -Router/gateway address | -
| 10.0.2.2 | -Special alias to your host loopback interface (i.e., 127.0.0.1 on your -development machine) | -
| 10.0.2.3 | -First DNS server | -
| 10.0.2.4 / 10.0.2.5 / 10.0.2.6 | -Optional second, third and fourth DNS server (if any) | -
| 10.0.2.15 | -The emulated device's own network/ethernet interface | -
| 127.0.0.1 | -The emulated device's own loopback interface | -
Note that the same address assignments are used by all running emulator -instances. That means that if you have two instances running concurrently on -your machine, each will have its own router and, behind that, each will have an -IP address of 10.0.2.15. The instances are isolated by a router and can -not see each other on the same network. For information about how to -let emulator instances communicate over TCP/UDP, see Connecting Emulator Instances.
- -Also note that the address 127.0.0.1 on your development machine corresponds -to the emulator's own loopback interface. If you want to access services running -on your development machine's loopback interface (a.k.a. 127.0.0.1 on your -machine), you should use the special address 10.0.2.2 instead.
- -Finally, note that each emulated device's pre-allocated addresses are -specific to the Android emulator and will probably be very different on real -devices (which are also very likely to be NAT-ed, i.e., behind a -router/firewall)
- - -Each emulator instance runs behind a virtual router, but unlike an actual -device connected to a physical router, the emulated device doesn't have access -to a physical network. Instead it runs as part of a normal application on your -development machine. This means that it is subject to the same networking -limitations as other applications on your machine:
- -The emulator's virtual router should be able to handle all outbound TCP and -UDP connections/messages on behalf of the emulated device, provided your -development machine's network environment allows it to do so. There are no -built-in limitations on port numbers or ranges except the one imposed by your -host operating system and network.
- -Depending on the environment, the emulator may not be able to support other -protocols (such as ICMP, used for "ping") might not be supported. Currently, the -emulator does not support IGMP or multicast.
- - -To communicate with an emulator instance behind its virtual router, you need -to set up network redirections on the virtual router. Clients can then connect -to a specified guest port on the router, while the router directs traffic -to/from that port to the emulated device's host port.
- -To set up the network redirections, you create a mapping of host and guest -ports/addresses on the the emulator instance. There are two ways to set up -network redirections: using emulator console commands and using the ADB tool, as -described below.
- - -Each emulator instance provides a control console the you can connect to, to
-issue commands that are specific to that instance. You can use the
-redir console command to set up redirections as needed for an
-emulator instance.
First, determine the console port number for the target emulator instance. -For example, the console port number for the first emulator instance launched is -5554. Next, connect to the console of the target emulator instance, specifying -its console port number, as follows:
- -telnet localhost 5554
-
-Once connected, use the redir command to work with redirections.
-To add a redirection, use:.
add <protocol>:<host-port>:<guest-port>
-
-
-where <protocol> is either tcp or udp,
-and <host-port> and <guest-port> sets the
-mapping between your own machine and the emulated system, respectively.
For example, the following command sets up a redirection that will handle all -incoming TCP connections to your host (development) machine on 127.0.0.1:5000 -and will pass them through to the emulated system's 10.0.2.15:6000.:
- -redir add tcp:5000:6000- -
To delete a redirection, you can use the redir del command. To
-list all redirections for a specific instance, you can use redir
-list. For more information about these and other console commands, see
-Using the Emulator Console.
Note that port numbers are restricted by your local environment. this typically
-means that you cannot use host port numbers under 1024 without special
-administrator privileges. Also, you won't be able to set up a redirection for a
-host port that is already in use by another process on your machine. In that
-case, redir generates an error message to that effect.
The Android Debug Bridge (ADB) tool provides port forwarding, an alternate -way for you to set up network redirections. For more information, see Forwarding Ports in the ADB -documentation.
- -Note that ADB does not currently offer any way to remove a redirection, -except by killing the ADB server.
- - -At startup, the emulator reads the list of DNS servers that your system is -currently using. It then stores the IP addresses of up to four servers on this -list and sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, -10.0.2.5 and 10.0.2.6 as needed.
- -On Linux and OS X, the emulator obtains the DNS server addresses by parsing
-the file /etc/resolv.conf. On Windows, the emulator obtains the
-addresses by calling the GetNetworkParams() API. Note that this
-usually means that the emulator ignores the content of your "hosts" file
-(/etc/hosts on Linux/OS X, %WINDOWS%/system32/HOSTS
- on Windows).
When starting the emulator at the command line, you can also use the
--dns-server <serverList> option to manually specify the
-addresses of DNS servers to use, where <serverList> is a comma-separated
-list of server names or IP addresses. You might find this option useful if you
-encounter DNS resolution problems in the emulated network (for example, an
-"Unknown Host error" message that appears when using the web browser).
If your emulator must access the Internet through a proxy server, you can use
-the -http-proxy <proxy> option when starting the emulator, to
-set up the appropriate redirection. In this case, you specify proxy information
-in <proxy> in one of these formats:
http://<machineName>:<port>- -
or
- -http://<username>:<password>@<machineName>:<port>- -
The -http-proxy option forces the emulator to use the specified
-HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not
-currently supported.
Alternatively, you can define the environment variable
-http_proxy to the value you want to use for
-<proxy>. In this case, you do not need to specify a value for
-<proxy> in the -http-proxy command — the
-emulator checks the value of the http_proxy environment variable at
-startup and uses its value automatically, if defined.
You can use the -verbose-proxy option to diagnose proxy
-connection problems.
To allow one emulator instance to communicate with another, you must set up -the necessary network redirections as illustrated below.
- -Assume that your environment is
- -and you want to run a server on B, to which C will connect, here is how you -could set it up:
- -10.0.2.15:<serverPort>A:localhost:<localPort> to
-B:10.0.2.15:<serverPort>For example, if you wanted to run an HTTP server, you can select
-<serverPort> as 80 and <localPort> as
-8080:
redir add tcp:8080:80The emulator automatically forwards simulated voice calls and SMS messages from one instance to another. To send a voice call or SMS, you use the dialer application and SMS application (if available) installed on one emulator
- -To initiate a simulated voice call to another emulator instance:
-To send an SMS message to another emulator instance, launch the SMS application (if available). Specify the console port number of the target emulator instance as as the SMS address, enter the message text, and send the message. The message is delivered to the target emulator instance.
- -You can also connect to an emulator instance's console to simulate an incoming voice call or SMS. For more information, see Telephony Emulation and SMS Emulation. - - - -
Each running emulator instance includes a console facility that lets you dynamically query and control the simulated device environment. For example, you can use the console to dynamically manage port redirections and network characteristics and simulate telephony events. To access the console and enter commands, you use telnet to connect to the console's port number.
-To connect to the console of any running emulator instance at any time, use this command:
- -telnet localhost <console-port>- -
An emulator instance occupies a pair of adjacent ports: a console port and an adb port. The port numbers differ by 1, with the adb port having the higher port number. The console of the first emulator instance running on a given machine uses console port 5554 and adb port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, 5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility.
- -To connect to the emulator console, you must specify a valid console port. If multiple emulator instances are running, you need to determine the console port of the emulator instance you want to connect to. You can find the instance's console port listed in the title of the instance window. For example, here's the window title for an instance whose console port is 5554:
- -Android Emulator (5554)
Alternatively, you can use the adb devices command, which prints a list of running emulator instances and their console port numbers. For more information, see Querying for Emulator/Device Instances in the adb documentation.
Note: The emulator listens for connections on ports 5554-5587 and accepts connections only from localhost.
- -Once you are connected to the console, you can then enter help [command] to see a list of console commands and learn about specific commands.
To exit the console session, use quit or exit.
The sections below describe the major functional areas of the console.
- - - -You can use the console to add and remove port redirections while the emulator is running. After connecting to the console, you can manage port redirections in this way:
-redir <list|add|del>- -
The redir command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
list |
- List the current port redirections. | -- |
add <protocol>:<host-port>:<guest-port> |
- Add a new port redirection. | -|
del <protocol>:<host-port> |
- Delete a port redirection. | -See above for meanings of <protocol> and <host-port>. | -
The console provides commands to let you set the geo position used by an emulator emulated device. You can use the geo command to send a simple GPS fix to the emulator, without needing to use NMEA 1083 formatting. The usage for the command is:
geo <fix|nmea>- -
The geo command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
fix <longitude> <latitude> [<altitude>] |
- Send a simple GPS fix to the emulator instance. | -Specify longitude and latitude in decimal degrees. Specify altitude in meters. | -
nmea <sentence> |
- Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem. | -<sentence> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are currently supported. |
-
You can issue the geo command to fix the GPS location as soon as an emulator instance is running. The emulator creates a mock location provider that sends it to GPS-aware applications as soon as they start and register location listeners. Any application can query the location manager to obtain the current GPS fix for the emulated device by calling:
-
-
LocationManager.getLastKnownLocation("gps")
-
-For more information about the Location Manager, see {@link android.location.LocationManager} and its methods.
- - -You can use the event command to send various events to the emulator.The usage for the command is:
event <send|types|codes|text>- -
The event command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
send <type>:<code>:<value> [...] |
- Send one or more events to the Android kernel. | -You can use text names or integers for <type> and <value>. |
-
types |
- List all <type> string aliases supported by the event subcommands. |
-- |
codes <type> |
- List all <codes> string aliases supported by the event
- subcommands for the specified <type>. |
-- |
event text <message> |
- Simulate keypresses to send the specified string of characters as a message, | -The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently. | -
You can use the power command to control the simulated power state of the emulator instance.The usage for the command is:
power <display|ac|status|present|health|capactiy>- -
The event command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
display |
- Display battery and charger state. | -- |
ac <on|off> |
- Set AC charging state to on or off. | -- |
status <unknown|charging|discharging|not-charging|full> |
- Change battery status as specified. | -- |
present <true|false> |
- Set battery presence state. | -- |
health <unknown|good|overheat|dead|overvoltage|failure> |
- Set battery health state. | -- |
power health <percent> |
- Set remaining battery capacity state (0-100). | -- |
You can use the console to check the network status and current delay and speed characteristics. To do so, connect to the console and use the netstatus command. Here's an example of the command and its output.
network status -- - -
The emulator lets you simulate various network latency levels, so that you can test your applicaton in an environment more typical of the actual conditions in which it will run. You can set a latency level or range at emulator startup or you can use the console to change the latency dynamically, while the application is running in the emulator.
-To set latency at emulator startup, use the -netdelay emulator option with a supported <delay> value, as listed in the table below. Here are some examples:
emulator -netdelay gprs -emulator -netdelay 40 100- -
To make dynamic changes to network delay while the emulator is running, connect to the console and use the netdelay command with a supported <delay> value from the table below.
network delay gprs- -
The format of network
| Value - | Description | Comments |
|---|---|---|
gprs | GPRS | -(min 150, max 550) | -
edge | EDGE/EGPRS | -(min 80, max 400) | -
umts | UMTS/3G | -(min 35, max 200) | -
none | No latency | (min 0, max 0) |
<num> |
-Emulate an exact latency (milliseconds). | -|
<min>:<max> |
-Emulate an specified latency range (min, max milliseconds). | -
The emulator also lets you simulate various network transfer rates. You can set a transfer rate or range at emulator startup or you can use the console to change the rate dynamically, while the application is running in the emulator.
-To set the network speed at emulator startup, use the -netspeed emulator option with a supported <speed> value, as listed in the table below. Here are some examples:
emulator -netspeed gsm -emulator -netspeed 14.4 80- -
To make dynamic changes to network speed while the emulator is running, connect to the console and use the netspeed command with a supported <speed> value from the table below.
network speed 14.4 80- -
The format of network <speed> is one of the following (numbers are
-kilobits/sec):
| Value - | Description | Comments |
|---|---|---|
gsm |
- GSM/CSD | (Up: 14.4, down: 14.4) |
hscsd |
- HSCSD | (Up: 14.4, down: 43.2) |
gprs |
- GPRS | (Up: 40.0, down: 80.0) |
edge |
- EDGE/EGPRS | -(Up: 118.4, down: 236.8) | -
umts |
- UMTS/3G | (Up: 128.0, down: 1920.0) |
hsdpa |
- HSDPA | (Up: 348.0, down: 14400.0) |
full |
- no limit | (Up: 0.0, down: 0.0) |
<num> |
- Set an exact rate used for both upload and download. | |
<up>:<down> |
- Set exact rates for upload and download separately. |
The Android emulator includes its own GSM emulated modem that lets you simulate telephony functions in the emulator. For example, you can simulate inbound phone calls and establish/terminate data connections. The Android system handles simulated calls exactly as it would actual calls. The emulator does not support call audio in this release.
-You can use the console to access the emulator's telephony functions. After connecting to the console, you can use
-gsm <call|accept|busy|cancel|data|hold|list|voice|status>-
to invoke telephony functions.
-The gsm command supports the subcommands listed in the table below.
| Subcommand | -Description | -Comments | -
|---|---|---|
call <phonenumber> |
- Simulate an inbound phone call from <phonenumber>. | -- |
accept <phonenumber> |
- Accept an inbound call from <phonenumber> and change the call's state "active". | -You can change a call's state to "active" only if its current state is "waiting" or "held". | -
busy <phonenumber> |
- Close an outbound call to <phonenumber> and change the call's state to "busy". | -You can change a call's state to "busy" only if its current state is "waiting". | -
cancel <phonenumber> |
- Terminate an inbound or outbound phone call to/from <phonenumber>. | -- |
data <state> |
- Change the state of the GPRS data connection to <state>. | -Supported <state> values are: - unregistered -- No network availablehome -- On local network, non-roamingroaming -- On roaming networksearching -- Searching networksdenied -- Emergency calls onlyoff -- Same as 'unregistered'on -- same as 'home' |
-
hold |
- Change the state of a call to "held". | -You can change a call's state to "held" only if its current state is "active" or "waiting". | -
list |
- List all inbound and outbound calls and their states. | -- |
voice <state> |
- Change the state of the GPRS voice connection to <state>. | -Supported <state> values are: - unregistered -- No network availablehome -- On local network, non-roamingroaming -- On roaming networksearching -- Searching networksdenied -- Emergency calls onlyoff -- Same as 'unregistered'on -- Same as 'home' |
-
status |
- Report the current GSM voice/data state. | -Values are those described for the voice and data commands. |
-
The Android emulator console lets you generate an SMS message and direct it to an emulator instance. Once you connect to an emulator instance, you can generate an emulated incoming SMS using this command:
- -sms send <senderPhoneNumber> <textmessage>- -
where <senderPhoneNumber> contains an arbitrary numeric string.
The console forwards the SMS message to the Android framework, which passes it through to an application that handles that message type.
- - - -You can use the vm command to control the VM on an emulator instance.The usage for the command is:
vm <start|stop|status>- -
The vm command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
start |
- Start the VM on the instance. | -- |
stop |
- Stop the VM on the instance. | -- |
start |
- Display the current status of the VM (running or stopped). | -- |
You can use the window command to manage the emulator window. The usage for the command is:
window <scale>- -
The vm command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
scale <scale> |
- Scale the emulator window. | -<scale> must be a number between 0.1 and 3 that describes the desired scaling factor. You can - also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" - tells the emulator to select the best window size. | -
You can terminate an emulator instance through the console, using the kill command.
You can run the emulator with any of four default skins, as described in the table below. To specify a skin, use -skin <skinID> when starting the emulator.
For example:
- -emulator -skin HVGA-L- -
Note that you must enter the <skinID> in uppercase letters (if your development computer is case-sensitive).
| skinID | -Description | -Skin | -
|---|---|---|
HVGA-L |
- 480x320, landscape | -![]() |
-
HVGA-P |
- 320x480, portrait (default) | -![]() |
-
QVGA-L |
- 320x240, landscape | -![]() |
-
QVGA-P |
- 240x320, portrait | -![]() |
-
You can run multiple instances of the emulator concurrently, if necessary. Each emulator instance can use a separate user-data image file and a different console port. This lets you manage each instance in isolation.
- -However, if you will run multiple emulator instances, note that there are limitations on the capability of each instance to maintain its persistent user data — user settings and installed applications — across sessions. Specifically:
- -~/.android/SDK-1.0/userdata-qemu.img (on Linux and Mac) or C:\Documents and Settings\<user>\Local
- Settings\Application Data\Android\SDK-1.0\userdata-qemu.img (on Windows) in your development computer.To run multiple emulator instances and let each maintain user data across sessions, start the instances with the -data option (see Startup Options) and supply the path to a user-data file.
If you don't have access to Eclipse or the ADT Plugin, you can install -your application on the emulator using -the adb utility. Before installing the application, you need to package it -in a .apk file using the Android Asset Packaging Tool. -Once the application is installed, you can start the emulator from the command -line, as described in this document, using any startup options necessary. -When the emulator is running, you can also connect to the emulator instance's -console to issue commands as needed.
- -As you update your code, you periodically package and install it on the emulator.
-The emulator preserves the application and its state data across restarts,
-in a user-data disk partition. To ensure that the application runs properly
-as you update it, you may need to delete the emulator's user-data partition.
-To do so, start the emulator with the -wipe-data option.
-For more information about the user-data partition and other emulator storage,
-see Working with Emulator Disk Images.
You can create a disk image and then load it to the emulator at startup, to simulate the presence of a user's SD card in the device. The sections below describe how to create the disk image, how to copy files to it, and how to load it in the emulator at startup.
- -Note that you can only load disk image at emulator startup. Similarly, you can not remove a simulated SD card from a running emulator. However, you can browse, send files to, and copy/remove files from a simulated SD card either with adb or the emulator.
- -The emulator supports emulated SDHC cards, so you can create an SD card image of any size up to 128 gigabytes.
- - - -You can use the mksdcard tool, included in the SDK, to create a FAT32 disk image that you can load in the emulator at startup. You can access mksdcard in the tools/ directory of the SDK and create a disk image like this:
- -mksdcard <size> <file>- -
For example:
- -mksdcard 1024M sdcard1.iso- -
For more information, see Other Tools.
- - -Once you have created the disk image, you can copy files to it prior to loading it in the emulator. To copy files, you can mount the image as a loop device and then copy the files to it, or you can use a utility such as mtools to copy the files directly to the image. The mtools package is available for Linux, Mac, and Windows.
- - - - -To load FAT32 disk image in the emulator, start the emulator with the -sdcard flag and specify the name and path of your image (relative to the current working directory):
emulator -sdcard <filepath>- - - -
The adb utility sees the emulator as an actual physical device. For this reason, you might have to use the -d flag with some common adb commands, such as install. The -d flag lets you specify which of several connected devices to use as the target of a command. If you don't specify -d, the emulator will target the first device in its list. For more information about adb, see Android Debug Bridge.
For emulators running on Mac OS X, if you see an error "Warning: No DNS servers found" when starting the emulator, check to see whether you have an /etc/resolv.conf file. If not, please run the following line in a command window:
ln -s /private/var/run/resolv.conf /etc/resolv.conf- -
See Frequently Asked Questions for more troubleshooting information.
- - -In this release, the limitations of the emulator include:
-The Hierarchy Viewer application allows you to debug and optimize your user -interface. It provides a visual representation of the layout's View hierarchy -(the Layout View) and a magnified inspector of the display (the Pixel Perfect View). -
- -To get the Hierarchy Viewer started:
-hierarchyviewer from your SDK
- /tools directory.
- If you've navigated to a different window on the device, press Refresh Windows -to refresh the list of available windows on the right.
- -The Layout View offers a look at the View layout and properties. It has three views:
-
-
-Select a node in the Tree View to display the properties of that element in -the Properties View. When a node is selected, the Wire-frame View -also indicates the bounds of the element with a red rectangle. -Double click a node in the tree (or select it, and click Display -View) to open a new window with a rendering of that element.
- -The Layout View includes a couple other helpful features for debugging your layout: -Invalidate and Request Layout. These buttons execute the -respective View calls, {@link android.view.View#invalidate()} and {@link android.view.View#requestLayout()}, -on the View element currently selected in the tree. Calling these methods on any View can -be very useful when simultaneously running a debugger on your application.
- -The Tree View can be resized by adjusting the zoom slider, below -the diagram. The number of View elements in the window is also given here. You -should look for ways to minimize the number of Views. The fewer View elements there -are in a window, the faster it will perform.
- -If you interact with the device and change the focused View, the diagram will not automatically refresh. -You must reload the Layout View by clicking Load View Hierarchy. - - -
The Pixel Perfect View provides a magnified look at the current device window. It has three views:
-Click on an element in the Explorer View and a "layout box" will be drawn in the -Normal View to indicate the layout position of that element. The layout box uses multiple rectangles, to indicate the normal bounds, the padding and the margin (as needed). The purple or green rectangle indicates -the normal bounds of the element (the height and width). The inner white or black rectangle indicates -the content bounds, when padding is present. A black or white rectangle outside the normal purple/green -rectangle indicates any present margins. -(There are two colors for each rectangle, in order to provide the best contrast -based on the colors currently in the background.)
- -A very handy feature for designing your UI is the ability to overlay an image in the Normal and Loupe -Views. For example, you might have a mock-up image of how you'd like to layout your interface. -By selecting Load... from the controls in the Normal View, you can choose the -image from your computer and it will be placed atop the preview. Your chosen image will anchor at the bottom left corner of the screen. You can then adjust the opacity of the overlay and begin fine-tuning your layout to match the mock-up.
- -The Normal View and Loupe View refresh at regular intervals (5 seconds by default), but the -Explorer View does not. If you navigate away and focus on a different View, then you should refresh the -Explorer's hierarchy by clicking Load View Hierarchy. This is even true -when you're working in a window that holds multiple Views that are not always visible. If you do not, -although the previews will refresh, clicking a View in the Explorer will not provide the proper layout box -in the Normal View, because the hierarchy believes you are still focused on the prior View.
- -Optional controls include:
-
-
-The Android SDK includes a variety of custom tools that help you develop mobile -applications on the Android platform. The most important of these are the Android -Emulator and the Android Development Tools plugin for Eclipse, but the SDK also -includes a variety of other tools for debugging, packaging, and installing your -applications on the emulator.
- -The Monkey is a program that runs on your -emulator or device and generates pseudo-random -streams of user events such as clicks, touches, or gestures, as well as a number of system-level -events. You can use the Monkey to stress-test applications that you are developing, in a random -yet repeatable manner.
- - -The Monkey is a command-line tool that that you can run on any emulator -instance or on a device. It sends a pseudo-random stream of -user events into the system, which acts as a stress test on the application software you are -developing.
- -The Monkey includes a number of options, but they break down into four primary -categories:
- -When the Monkey runs, it generates events and sends them to the system. It also watches -the system under test and looks for three conditions, which it treats specially:
- -Depending on the verbosity level you have selected, you will also see reports on the progress -of the Monkey and the events being generated.
- - -You can launch the Monkey using a command line on your development machine or from a script.
-Because the Monkey runs in the emulator/device environment, you must launch it from a shell in
-that environment. You can do this by prefacing adb shell to each command,
-or by entering the shell and entering Monkey commands directly.
The basic syntax is:
- -$ adb shell monkey [options] <event-count>- -
With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send -events to any (and all) packages installed on your target. Here is a more typical command line, -which will launch your application and send 500 pseudo-random events to it:
- -$ adb shell monkey -p your.package.name -v 500- - -
The table below lists all options you can include on the Monkey command line.
- -| Category | -Option | -Description | -
|---|---|---|
| General | ---help |
-Prints a simple usage guide. | -
-v |
-Each -v on the command line will increment the verbosity level. -Level 0 (the default) provides little information beyond startup notification, test completion, and -final results. -Level 1 provides more details about the test as it runs, such as individual events being sent to -your activities. -Level 2 provides more detailed setup information such as activities selected or not selected for -testing. | -|
| Events | --s <seed> |
-Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed -value, it will generate the same sequence of events. | -
--throttle <milliseconds> |
-Inserts a fixed delay between events. You can use this option to slow down the Monkey. -If not specified, there is no delay and the events are generated as rapidly as possible. | -|
--pct-touch <percent> |
-Adjust percentage of touch events. -(Touch events are a down-up event in a single place on the screen.) | -|
--pct-motion <percent> |
-Adjust percentage of motion events. -(Motion events consist of a down event somewhere on the screen, a series of pseudo-random -movements, and an up event.) | -|
--pct-trackball <percent> |
-Adjust percentage of trackball events. -(Trackball events consist of one or more random movements, sometimes followed by a click.) | -|
--pct-nav <percent> |
-Adjust percentage of "basic" navigation events. -(Navigation events consist of up/down/left/right, as input from a directional input device.) | -|
--pct-majornav <percent> |
-Adjust percentage of "major" navigation events. -(These are navigation events that will typically cause actions within your UI, such as -the center button in a 5-way pad, the back key, or the menu key.) | -|
--pct-syskeys <percent> |
-Adjust percentage of "system" key events. -(These are keys that are generally reserved for use by the system, such as Home, Back, Start Call, -End Call, or Volume controls.) | -|
--pct-appswitch <percent> |
-Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing -coverage of all activities within your package. | -|
--pct-anyevent <percent> |
-Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used -buttons on the device, and so forth. | -|
| Constraints | --p <allowed-package-name> |
-If you specify one or more packages this way, the Monkey will only allow the system -to visit activities within those packages. If your application requires access to activities in -other packages (e.g. to select a contact) you'll need to specify those packages as well. -If you don't specify any packages, the Monkey will allow the system to launch activities -in all packages. To specify multiple packages, use the -p option multiple times — one -p -option per package. | -
-c <main-category> |
-If you specify one or more categories this way, the Monkey will only allow the -system to visit activities that are listed with one of the specified categories. -If you don't specify any categories, the Monkey will select activities listed with the category -Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c -option multiple times — one -c option per category. | -|
| Debugging | ---dbg-no-events |
-When specified, the Monkey will perform the initial launch into a test activity, but -will not generate any further events. -For best results, combine with -v, one or more package constraints, and a non-zero throttle to keep the Monkey -running for 30 seconds or more. This provides an environment in which you can monitor package -transitions invoked by your application. | -
--hprof |
-If set, this option will generate profiling reports immediately before and after -the Monkey event sequence. -This will generate large (~5Mb) files in data/misc, so use with care. See -Traceview for more information -on trace files. | -|
--ignore-crashes |
-Normally, the Monkey will stop when the application crashes or experiences any type of -unhandled exception. If you specify this option, the Monkey will continue to send events to -the system, until the count is completed. | -|
--ignore-timeouts |
-Normally, the Monkey will stop when the application experiences any type of timeout error such -as a "Application Not Responding" dialog. If you specify this option, the Monkey will continue to -send events to the system, until the count is completed. | -|
--ignore-security-exceptions |
-Normally, the Monkey will stop when the application experiences any type of permissions error, -for example if it attempts to launch an activity that requires certain permissions. If you specify -this option, the Monkey will continue to send events to the system, until the count is -completed. | -|
--kill-process-after-error |
-Normally, when the Monkey stops due to an error, the application that failed will be left -running. When this option is set, it will signal the system to stop the process in which the error -occurred. -Note, under a normal (successful) completion, the launched process(es) are not stopped, and -the device is simply left in the last state after the final event. | -|
--monitor-native-crashes |
-Watches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop. | -|
--wait-dbg |
-Stops the Monkey from executing until a debugger is attached to it. | -
The sections below describe other tools that you can use when building Android applications.
- -All of the tools are included in the Android SDK and are accessible from the tools/ directory.
The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the emulator, to simulate the presence of an SD card in the device. Here is the usage for mksdcard:
- -mksdcard [-l label] <size>[K|M] <file>- -The table below lists the available options/arguments - -
| Argument | -Description | -
|---|---|
-l |
- A volume label for the disk image to create. | -
size |
- An integer that specifies the size (in bytes) of disk image to create.
-You can also specify size in kilobytes or megabytes, by appending a "K" or "M" to <size>. For example, 1048576K, 1024M. |
-
file |
- The path/filename of the disk image to create. | -
Once you have created the disk image file, you can load it in the emulator at startup using the emulator's -sdcard option. For more information, see Android Emulator.
- -emulator -sdcard <file>- - - -
The dx tool lets you generate Android bytecode from .class files. The tool converts target files and/or directories to Dalvik executable format (.dex) files, so that they can run in the Android environment. It can also dump the class files in a human-readable format and run a target unit test. You can get the usage and options for this tool by using dx --help.
If you aren't using the Eclipse IDE and ADT plugin, you can use the the activitycreator script to get started with a new application. When you run the script, it creates the structure of a minimal Android application that you can build on and extend to meet your needs.
- -For Linux and Mac, the SDK provides activitycreator, a shell script, and for Windows activitycreator.bat, a batch script that runs an executable. Regardless of platform, the usage for the script is the same:
activitycreator [--out <folder>] [--ide intellij] your.package.name.ActivityName- -
| Option | -Description | -
|---|---|
--out <folder> |
- Specifies where to create the files/folders. | -
--ide intellij |
- Creates project files for IntelliJ | -
When run, the script creates these files:
- -When you are ready, you can use Ant to build the project so that you can run it on the emulator.
- -If you are using Eclipse with the ADT plugin, you do not need to use activitycreator. You can use the New Project Wizard, provided by the ADT plugin, instead.
- - diff --git a/docs/html/guide/developing/tools/traceview.jd b/docs/html/guide/developing/tools/traceview.jd deleted file mode 100644 index dd3f4bb..0000000 --- a/docs/html/guide/developing/tools/traceview.jd +++ /dev/null @@ -1,310 +0,0 @@ -page.title=Traceview: A Graphical Log Viewer -@jd:body - -Traceview is a graphical viewer for execution logs -saved by your application. The sections below describe how to use the program.
- -To use Traceview, you need to generate log files containing the trace information you want to analyze. To do that, you include the {@link android.os.Debug} - class in your code and call its methods to start and stop logging of trace information - to disk. When your application quits, you can then use Traceview to examine the log files - for useful run-time information such - as method calls and run times.
-To create the trace files, include the {@link android.os.Debug} class and call one - of the {@link android.os.Debug#startMethodTracing() startMethodTracing()} methods. - In the call, you specify a base name for the trace files that the system generates. - To stop tracing, call {@link android.os.Debug#stopMethodTracing() stopMethodTracing()}. - These methods start and stop method tracing across the entire virtual machine. For - example, you could call startMethodTracing() in your activity's onCreate() - method, and call stopMethodTracing() in that activity's onDestroy() method.
- -
- // start tracing to "/sdcard/calc.trace"
- Debug.startMethodTracing("calc");
- // ...
- // stop tracing
- Debug.stopMethodTracing();
-
-
-When your application calls startMethodTracing(), the system creates a
-file called <trace-base-name>.trace. This contains the
-binary method trace data and a mapping table with thread and method names.
The system then begins buffering the generated trace data, until your application calls - stopMethodTracing(), at which time it writes the buffered data to the - output file. - If the system reaches the maximum buffer size before stopMethodTracing() - is called, the system stops tracing and sends a notification - to the console.
- -Interpreted code will run more slowly when profiling is enabled. Don't -try to generate absolute timings from the profiler results (i.e. "function -X takes 2.5 seconds to run"). The times are only -useful in relation to other profile output, so you can see if changes -have made the code faster or slower.
- -When using the Android emulator, you must create an SD card image upon which
-the trace files will be written. For example, from the /tools directory, you
-can create an SD card image and mount it when launching the emulator like so:
-$ mksdcard 1024M ./imgcd -$ emulator -sdcard ./img --
For more information, read about the -mksdcard tool.
- -The format of the trace files is described later - in this document.
- - - -After your application has run and the system has created your trace files <trace-base-name>.trace
- on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy
- the files. Here's an example that shows how to copy an example file,
- calc.trace, from the default location on the emulator to the /tmp directory on
-the emulator host machine:
adb pull /sdcard/calc.trace /tmp- - - - -
To run traceview and view the trace files, enter traceview <trace-base-name>.
- For example, to run Traceview on the example files copied in the previous section,
- you would use:
traceview /tmp/calc- -
Traceview loads the log files and displays their data in a window that has two panels:
-The sections below provide addition information about the traceview output panes.
- - - -The image below shows a close up of the timeline panel. Each thread’s - execution is shown in its own row, with time increasing to the right. Each method - is shown in another color (colors are reused in a round-robin fashion starting - with the methods that have the most inclusive time). The thin lines underneath - the first row show the extent (entry to exit) of all the calls to the selected - method. The method in this case is LoadListener.nativeFinished() and it was - selected in the profile view.
-
The image below shows the profile pane. The profile pane shows a - summary of all the time spent in a method. The table shows - both the inclusive and exclusive times (as well as the percentage of the total - time). Exclusive time is the time spent in the method. Inclusive time is the - time spent in the method plus the time spent in any called functions. We refer - to calling methods as "parents" and called methods as "children." - When a method is selected (by clicking on it), it expands to show the parents - and children. Parents are shown with a purple background and children - with a yellow background. The last column in the table shows the number of calls - to this method plus the number of recursive calls. The last column shows the - number of calls out of the total number of calls made to that method. In this - view, we can see that there were 14 calls to LoadListener.nativeFinished(); looking - at the timeline panel shows that one of those calls took an unusually - long time.
-
Tracing creates two distinct pieces of output: a data file, - which holds the trace data, and a key file, which - provides a mapping from binary identifiers to thread and method names. - The files are concatenated when tracing completes, into a - single .trace file.
- -Note: The previous version of Traceview did not concatenate
-these files for you. If you have old key and data files that you'd still like to trace, you
-can concatenate them yourself with cat mytrace.key mytrace.data > mytrace.trace.
The data file is binary, structured as - follows (all values are stored in little-endian order):
-* File format:
-* header
-* record 0
-* record 1
-* ...
-*
-* Header format:
-* u4 magic 0x574f4c53 ('SLOW')
-* u2 version
-* u2 offset to data
-* u8 start date/time in usec
-*
-* Record format:
-* u1 thread ID
-* u4 method ID | method action
-* u4 time delta since start, in usec
-
-The application is expected to parse all of the header fields, then seek - to "offset to data" from the start of the file. From there it just - reads - 9-byte records until EOF is reached.
-u8 start date/time in usec is the output from gettimeofday(). - It's mainly there so that you can tell if the output was generated yesterday - or three months ago.
-method action sits in the two least-significant bits of the - method word. The currently defined meanings are:
-An unsigned 32-bit integer can hold about 70 minutes of time in microseconds. -
- - - -The key file is a plain text file divided into three sections. Each - section starts with a keyword that begins with '*'. If you see a '*' at the start - of a line, you have found the start of a new section.
-An example file might look like this:
-*version -1 -clock=global -*threads -1 main -6 JDWP Handler -5 Async GC -4 Reference Handler -3 Finalizer -2 Signal Handler -*methods -0x080f23f8 java/io/PrintStream write ([BII)V -0x080f25d4 java/io/PrintStream print (Ljava/lang/String;)V -0x080f27f4 java/io/PrintStream println (Ljava/lang/String;)V -0x080da620 java/lang/RuntimeException <init> ()V -[...] -0x080f630c android/os/Debug startMethodTracing ()V -0x080f6350 android/os/Debug startMethodTracing (Ljava/lang/String;Ljava/lang/String;I)V -*end-
clock=global, indicates that we use a common
- clock across all threads. A future version may use per-thread CPU time counters
- that are independent for every thread.Neither the threads nor methods sections are sorted.
- - -The Android SDK includes dmtracedump, a tool that gives you an alternate way - of generating graphical call-stack diagrams from trace log files. The tool - uses the Graphviz Dot utility to create the graphical output, so you need to - install Graphviz before running dmtracedump.
- -The dmtracedump tool generates the call stack data as a tree diagram, with each call - represented as a node. It shows call flow (from parent node to child nodes) using - arrows. The diagram below shows an example of dmtracedump output.
- -
-
-For each node, dmtracedump shows <ref> callname (<inc-ms>,
- <exc-ms>,<numcalls>), where
<ref> -- Call reference number, as used in trace logs<inc-ms> -- Inclusive elapsed time (milliseconds spent in method, including all child methods)<exc-ms> -- Exclusive elapsed time (milliseconds spent in method, not including any child methods)<numcalls> -- Number of callsThe usage for dmtracedump is:
- -dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>- -
The tool then loads trace log data from <trace-base-name>.data and <trace-base-name>.key. - The table below lists the options for dmtracedump.
- -| Option - | Description | -
|---|---|
-d <trace-base-name> |
- Diff with this trace name | -
-g <outfile> |
- Generate output to <outfile> | -
-h |
- Turn on HTML output | -
-o |
- Dump the trace file instead of profiling | -
-d <trace-base-name> |
- URL base to the location of the sortable javascript file | -
-t <percent> |
- Minimum threshold for including child nodes in the graph (child's inclusive - time as a percentage of parent inclusive time). If this option is not used, - the default threshold is 20%. | -
-Welcome to the Android Dev Guide! The Dev Guide is -a practical introduction to developing applications for Android. -It explores the concepts behind Android, the framework for -constructing an application, and the tools for developing, -testing, and publishing software for the platform. -
- --The Dev Guide holds most of the documentation for the Android -platform, except for reference material on the framework API. -For API specifications, go to the -Reference tab above. -
- --As you can see in the panel on the left, the Dev Guide is -divided into a handful of sections. They are: -
- -
-The first step in programming for Android is downloading the SDK -(software development kit). For instructions and information about -the kit, go to the SDK tab above. -
- --After you have the SDK, begin by looking over the Dev Guide. -If you want to start by getting a quick look at the code, the short -Hello World -tutorial walks you through a standard "Hello, World" application as -it would be written for the Android platform. The -Application -Fundamentals document is a good place to start for an -understanding of the application framework. -
- - --For additional help, consider joining one or more of the Android -discussion groups. Go to the -Community tab above -for more information. -
- -To return to this page later, just click the "Dev Guide" tab while any Dev Guide page is loaded.
\ No newline at end of file diff --git a/docs/html/guide/practices/design/index.jd b/docs/html/guide/practices/design/index.jd deleted file mode 100644 index a818831..0000000 --- a/docs/html/guide/practices/design/index.jd +++ /dev/null @@ -1,21 +0,0 @@ -page.title=Application Design Goals -@jd:body - -When learning how to build applications on a new platform, you first learn what APIs are available and how to use them. Later, you learn the nuances of the platform. Put another way: first you learn how you can build applications; later, you learn how you should build them, to ensure that your applications offer outstanding performance and a great user experience.
- -The documents below help you learn the nuances of Android and get started building great applications more quickly, They discuss important aspects of application design that directly influence the user experience of your application, when in the hands of a mobile device user. You should read and consider these design goals as you plan your application and throughout its development, especially if you are new to developing for mobile devices.
- -Successful mobile applications offer an outstanding user experience, in addition to a compelling technical feature set. The user experience is more than just its visual design or UI flow. It is also influenced by how well the application responds to the user's keypresses and other actions, how it well it interacts with other applications, and how fully and efficiently it uses device and system capabilities.
- -An outstanding user experience has three key characteristics: it is -fast; it is responsive; and it is seamless. Of course -every platform since the dawn of computing has probably cited those same three -qualities at one time or another. However, each platform achieves them in -different ways; the documents below explain how you can build Android -applications that are fast, responsive, and seamless.
- -An Android application should be fast. Well, it's probably more accurate to -say that it should be efficient. That is, it should execute as -efficiently as possible in the mobile device environment, with its limited -computing power and data storage, smaller screen, and constrained battery life. - -
As you develop your application, keep in mind that, while the application may -perform well enough in your emulator, running on your dual-core development -computer, it will not perform that well when run a mobile device — even -the most powerful mobile device can't match the capabilities of a typical -desktop system. For that reason, you should strive to write efficient code, to -ensure the best possible performance on a variety of mobile devices.
- -Generally speaking, writing fast or efficient code means keeping memory -allocations to a minimum, writing tight code, and avoiding certain language and -programming idioms that can subtly cripple performance. In object-oriented -terms, most of this work takes place at the method level, on the order of -actual lines of code, loops, and so on.
- -This document covers these topics:
-There are two basic rules for resource-constrained systems:
- -All the tips below follow from these two basic tenets.
- -Some would argue that much of the advice on this page amounts to "premature -optimization." While it's true that micro-optimizations sometimes make it -harder to develop efficient data structures and algorithms, on embedded -devices like handsets you often simply have no choice. For instance, if you -bring your assumptions about VM performance on desktop machines to Android, -you're quite likely to write code that exhausts system memory. This will bring -your application to a crawl — let alone what it will do to other programs -running on the system!
- -That's why these guidelines are important. Android's success depends on -the user experience that your applications provide, and that user experience -depends in part on whether your code is responsive and snappy, or slow and -aggravating. Since all our applications will run on the same devices, we're -all in this together, in a way. Think of this document as like the rules of -the road you had to learn when you got your driver's license: things run -smoothly when everybody follows them, but when you don't, you get your car -smashed up.
- -Before we get down to brass tacks, a brief observation: nearly all issues -described below are valid whether or not the VM features a JIT compiler. If I -have two methods that accomplish the same thing, and the interpreted execution -of foo() is faster than bar(), then the compiled version of foo() will -probably be as fast or faster than compiled bar(). It is unwise to rely on a -compiler to "save" you and make your code fast enough.
- - -Object creation is never free. A generational GC with per-thread allocation -pools for temporary objects can make allocation cheaper, but allocating memory -is always more expensive than not allocating memory.
- -If you allocate objects in a user interface loop, you will force a periodic -garbage collection, creating little "hiccups" in the user experience.
- -Thus, you should avoid creating object instances you don't need to. Some -examples of things that can help:
- -A somewhat more radical idea is to slice up multidimensional arrays into parallel -single one-dimension arrays:
- -Generally speaking, avoid creating short-term temporary objects if you -can. Fewer objects created mean less-frequent garbage collection, which has -a direct impact on user experience.
- - -When processing strings, don't hesitate to use specialty methods like -String.indexOf(), String.lastIndexOf(), and their cousins. These are typically -implemented in C/C++ code that easily runs 10-100x faster than doing the same -thing in a Java loop.
- -The flip side of that advice is that punching through to a native -method is more expensive than calling an interpreted method. Don't use native -methods for trivial computation, if you can avoid it.
- - -Suppose you have a HashMap object. You can declare it as a HashMap or as -a generic Map:
- -Map myMap1 = new HashMap(); -HashMap myMap2 = new HashMap();- -
Which is better?
- -Conventional wisdom says that you should prefer Map, because it -allows you to change the underlying implementation to anything that -implements the Map interface. Conventional wisdom is correct for -conventional programming, but isn't so great for embedded systems. Calling -through an interface reference can take 2x longer than a virtual -method call through a concrete reference.
- -If you have chosen a HashMap because it fits what you're doing, there -is little value in calling it a Map. Given the availability of -IDEs that refactor your code for you, there's not much value in calling -it a Map even if you're not sure where the code is headed. (Again, though, -public APIs are an exception: a good API usually trumps small performance -concerns.)
- - -If you don't need to access an object's fields, make your method static. It can -be called faster, because it doesn't require a virtual method table -indirection. It's also good practice, because you can tell from the method -signature that calling the method can't alter the object's state.
- - -In native languages like C++ it's common practice to use getters (e.g.
-i = getCount()) instead of accessing the field directly (i
-= mCount). This is an excellent habit for C++, because the compiler can
-usually inline the access, and if you need to restrict or debug field access
-you can add the code at any time.
On Android, this is a bad idea. Virtual method calls are expensive, -much more so than instance field lookups. It's reasonable to follow -common object-oriented programming practices and have getters and setters -in the public interface, but within a class you should always access -fields directly.
- - -Accessing object fields is much slower than accessing local variables. -Instead of writing:
-for (int i = 0; i < this.mCount; i++) - dumpItem(this.mItems[i]);- -
You should write:
-int count = this.mCount; - Item[] items = this.mItems; - - for (int i = 0; i < count; i++) - dumpItems(items[i]); -- -
(We're using an explicit "this" to make it clear that these are -member variables.)
- -A similar guideline is never call a method in the second clause of a "for" -statement. For example, the following code will execute the getCount() method -once per iteration, which is a huge waste when you could have simply cached -the value as an int:
- -for (int i = 0; i < this.getCount(); i++) - dumpItems(this.getItem(i)); -- -
It's also usually a good idea to create a local variable if you're going to be -accessing an instance field more than once. For example:
- -
- protected void drawHorizontalScrollBar(Canvas canvas, int width, int height) {
- if (isHorizontalScrollBarEnabled()) {
- int size = mScrollBar.getSize(false);
- if (size <= 0) {
- size = mScrollBarSize;
- }
- mScrollBar.setBounds(0, height - size, width, height);
- mScrollBar.setParams(
- computeHorizontalScrollRange(),
- computeHorizontalScrollOffset(),
- computeHorizontalScrollExtent(), false);
- mScrollBar.draw(canvas);
- }
- }
-
-That's four separate lookups of the member field mScrollBar.
-By caching mScrollBar in a local stack variable, the four member field lookups
-become four stack variable references, which are much more efficient.
Incidentally, method arguments have the same performance characteristics -as local variables.
- - -Consider the following declaration at the top of a class:
- -static int intVal = 42; -static String strVal = "Hello, world!";- -
The compiler generates a class initializer method, called
-<clinit>, that is executed when the class is first used.
-The method stores the value 42 into intVal, and extracts a
-reference from the classfile string constant table for strVal.
-When these values are referenced later on, they are accessed with field
-lookups.
We can improve matters with the "final" keyword:
- -static final int intVal = 42; -static final String strVal = "Hello, world!";- -
The class no longer requires a <clinit> method,
-because the constants go into classfile static field initializers, which are
-handled directly by the VM. Code accessing intVal will use
-the integer value 42 directly, and accesses to strVal will
-use a relatively inexpensive "string constant" instruction instead of a
-field lookup.
Declaring a method or class "final" does not confer any immediate -performance benefits, but it does allow certain optimizations. For example, if -the compiler knows that a "getter" method can't be overridden by a sub-class, -it can inline the method call.
- -You can also declare local variables final. However, this has no definitive -performance benefits. For local variables, only use "final" if it makes the -code clearer (or you have to, e.g. for use in an anonymous inner class).
- - -The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections that implement the Iterable interface. -With these objects, an iterator is allocated to make interface calls -to hasNext() and next(). With an ArrayList, you're better off walking through -it directly, but for other collections the enhanced for loop syntax will be equivalent -to explicit iterator usage.
- -Nevertheless, the following code shows an acceptable use of the enhanced for loop:
- -public class Foo {
- int mSplat;
- static Foo mArray[] = new Foo[27];
-
- public static void zero() {
- int sum = 0;
- for (int i = 0; i < mArray.length; i++) {
- sum += mArray[i].mSplat;
- }
- }
-
- public static void one() {
- int sum = 0;
- Foo[] localArray = mArray;
- int len = localArray.length;
-
- for (int i = 0; i < len; i++) {
- sum += localArray[i].mSplat;
- }
- }
-
- public static void two() {
- int sum = 0;
- for (Foo a: mArray) {
- sum += a.mSplat;
- }
- }
-}
-
-zero() retrieves the static field twice and gets the array -length once for every iteration through the loop.
- -one() pulls everything out into local variables, avoiding -the lookups.
- -two() uses the enhanced for loop syntax introduced in version 1.5 of -the Java programming language. The code generated by the compiler takes care -of copying the array reference and the array length to local variables, making -it a good choice for walking through all elements of an array. It does -generate an extra local load/store in the main loop (apparently preserving -"a"), making it a teensy bit slower and 4 bytes longer than one().
- -To summarize all that a bit more clearly: enhanced for loop syntax performs well -with arrays, but be cautious when using it with Iterable objects since there is -additional object creation.
- - -Enums are very convenient, but unfortunately can be painful when size -and speed matter. For example, this:
- -public class Foo {
- public enum Shrubbery { GROUND, CRAWLING, HANGING }
-}
-
-turns into a 900 byte .class file (Foo$Shrubbery.class). On first use, the -class initializer invokes the <init> method on objects representing each -of the enumerated values. Each object gets its own static field, and the full -set is stored in an array (a static field called "$VALUES"). That's a lot of -code and data, just for three integers.
- -This:
- -Shrubbery shrub = Shrubbery.GROUND;- -
causes a static field lookup. If "GROUND" were a static final int, -the compiler would treat it as a known constant and inline it.
- -The flip side, of course, is that with enums you get nicer APIs and -some compile-time value checking. So, the usual trade-off applies: you should -by all means use enums for public APIs, but try to avoid them when performance -matters.
- -In some circumstances it can be helpful to get enum integer values
-through the ordinal() method. For example, replace:
for (int n = 0; n < list.size(); n++) {
- if (list.items[n].e == MyEnum.VAL_X)
- // do stuff 1
- else if (list.items[n].e == MyEnum.VAL_Y)
- // do stuff 2
-}
-
-with:
- - int valX = MyEnum.VAL_X.ordinal();
- int valY = MyEnum.VAL_Y.ordinal();
- int count = list.size();
- MyItem items = list.items();
-
- for (int n = 0; n < count; n++)
- {
- int valItem = items[n].e.ordinal();
-
- if (valItem == valX)
- // do stuff 1
- else if (valItem == valY)
- // do stuff 2
- }
-
-In some cases, this will be faster, though this is not guaranteed.
- - -Consider the following class definition:
- -public class Foo {
- private int mValue;
-
- public void run() {
- Inner in = new Inner();
- mValue = 27;
- in.stuff();
- }
-
- private void doStuff(int value) {
- System.out.println("Value is " + value);
- }
-
- private class Inner {
- void stuff() {
- Foo.this.doStuff(Foo.this.mValue);
- }
- }
-}
-
-The key things to note here are that we define an inner class (Foo$Inner) -that directly accesses a private method and a private instance field -in the outer class. This is legal, and the code prints "Value is 27" as -expected.
- -The problem is that Foo$Inner is technically (behind the scenes) a totally -separate class, which makes direct access to Foo's private -members illegal. To bridge that gap, the compiler generates a -couple of synthetic methods:
- -/*package*/ static int Foo.access$100(Foo foo) {
- return foo.mValue;
-}
-/*package*/ static void Foo.access$200(Foo foo, int value) {
- foo.doStuff(value);
-}
-
-The inner-class code calls these static methods whenever it needs to -access the "mValue" field or invoke the "doStuff" method in the outer -class. What this means is that the code above really boils down to a case -where you're accessing member fields through accessor methods instead of -directly. Earlier we talked about how accessors are slower than direct field -accesses, so this is an example of a certain language idiom resulting in an -"invisible" performance hit.
- -We can avoid this problem by declaring fields and methods accessed -by inner classes to have package scope, rather than private scope. -This runs faster and removes the overhead of the generated methods. -(Unfortunately it also means the fields could be accessed directly by other -classes in the same package, which runs counter to the standard OO -practice of making all fields private. Once again, if you're -designing a public API you might want to carefully consider using this -optimization.)
- - -Before the release of the Pentium CPU, it was common for game authors to do -as much as possible with integer math. With the Pentium, the floating point -math co-processor became a built-in feature, and by interleaving integer and -floating-point operations your game would actually go faster than it would -with purely integer math. The common practice on desktop systems is to use -floating point freely.
- -Unfortunately, embedded processors frequently do not have hardware floating -point support, so all operations on "float" and "double" are performed in -software. Some basic floating point operations can take on the order of a -millisecond to complete.
- -Also, even for integers, some chips have hardware multiply but lack -hardware divide. In such cases, integer division and modulus operations are -performed in software — something to think about if you're designing a -hash table or doing lots of math.
- - -To illustrate some of our ideas, here is a table listing the approximate -run times for a few basic actions. Note that these values should NOT be taken -as absolute numbers: they are a combination of CPU and wall clock time, and -will change as improvements are made to the system. However, it is worth -noting how these values apply relative to each other — for example, -adding a member variable currently takes about four times as long as adding a -local variable.
- -| Action | -Time | -
|---|---|
| Add a local variable | -1 | -
| Add a member variable | -4 | -
| Call String.length() | -5 | -
| Call empty static native method | -5 | -
| Call empty static method | -12 | -
| Call empty virtual method | -12.5 | -
| Call empty interface method | -15 | -
| Call Iterator:next() on a HashMap | -165 | -
| Call put() on a HashMap | -600 | -
| Inflate 1 View from XML | -22,000 | -
| Inflate 1 LinearLayout containing 1 TextView | -25,000 | -
| Inflate 1 LinearLayout containing 6 View objects | -100,000 | -
| Inflate 1 LinearLayout containing 6 TextView objects | -135,000 | -
| Launch an empty activity | -3,000,000 | -
The best way to write good, efficient code for embedded systems is to -understand what the code you write really does. If you really want to allocate -an iterator, by all means use enhanced for loop syntax on a List; just make it a -deliberate choice, not an inadvertent side effect.
- -Forewarned is forearmed! Know what you're getting into! Insert your -favorite maxim here, but always think carefully about what your code is doing, -and be on the lookout for ways to speed it up.
diff --git a/docs/html/guide/practices/design/responsiveness.jd b/docs/html/guide/practices/design/responsiveness.jd deleted file mode 100644 index ecd743d..0000000 --- a/docs/html/guide/practices/design/responsiveness.jd +++ /dev/null @@ -1,117 +0,0 @@ -page.title=Designing for Responsiveness -@jd:body - -It's possible to write code that wins every performance test in the world, but still sends users in a fiery rage when they try to use the application. These are the applications that aren't responsive enough — the ones that feel -sluggish, hang or freeze for significant periods, or take too long to process -input.
- -In Android, the system guards against applications that are insufficiently responsive for a period of time by displaying a dialog to the user, called the Application Not Responding (ANR) dialog. The user can choose to let the application continue, but the user won't appreciate having to act on this dialog every time he or she uses your application. So it's important to design responsiveness into your application, so that the system never has cause to display an ANR to the user.
- -Generally, the system displays an ANR if an application cannot respond to user input. For example, if an application blocks on some I/O operation (frequently a network access), then the main application thread won't be able to process incoming user input events. After a time, the system concludes that the application has hung, and displays the ANR to give the user the option to kill it. - -
Similarly, if your application spends too much time building an elaborate in-memory -structure, or perhaps computing the next move in a game, the system will -conclude that your application has hung. It's always important to make -sure these computations are efficient using the techniques above, but even the -most efficient code still takes time to run.
- -In both of these cases, the fix is usually to create a child thread, and do -most of your work there. This keeps the main thread (which drives the user -interface event loop) running, and prevents the system from concluding your code -has frozen. Since such threading usually is accomplished at the class -level, you can think of responsiveness as a class problem. (Compare -this with basic performance, which was described above as a method-level -concern.)
- -
-An ANR dialog displayed to the user.
-This document discusses how the Android system determines whether an application is -not responding and provides guidelines for -ensuring that your application is responsive.
- -This document covers these topics:
- - -In Android, application responsiveness is monitored by the Activity Manager -and Window Manager system services. Android will display the ANR dialog -for a particular application when it detects one of the following -conditions:
-Given the above definition for ANR, let's examine why this can occur in -Android applications and how best to structure your application to avoid ANR.
- -Android applications normally run entirely on a single (i.e. main) thread. -This means that anything your application is doing in the main thread that -takes a long time to complete can trigger the ANR dialog because your -application is not giving itself a chance to handle the input event or Intent -broadcast.
- -Therefore any method that runs in the main thread should do as little work
-as possible. In particular, Activities should do as little as possible to set
-up in key life-cycle methods such as onCreate() and
-onResume(). Potentially long running operations such as network
-or database operations, or computationally expensive calculations such as
-resizing bitmaps should be done in a child thread (or in the case of databases
-operations, via an asynchronous request). However, this does not mean that
-your main thread should block while waiting for the child thread to
-complete — nor should you call Thread.wait() or
-Thread.sleep(). Instead of blocking while waiting for a child
-thread to complete, your main thread should provide a {@link
-android.os.Handler Handler} for child threads to post back to upon completion.
-Designing your application in this way will allow your main thread to remain
-responsive to input and thus avoid ANR dialogs caused by the 5 second input
-event timeout. These same practices should be followed for any other threads
-that display UI, as they are also subject to the same timeouts.
The specific constraint on IntentReciever execution time emphasizes what -they were meant to do: small, discrete amounts of work in the background such -as saving a setting or registering a Notification. So as with other methods -called in the main thread, applications should avoid potentially long-running -operations or calculations in BroadcastReceivers. But instead of doing intensive -tasks via child threads (as the life of a BroadcastReceiver is short), your -application should start a {@link android.app.Service Service} if a -potentially long running action needs to be taken in response to an Intent -broadcast. As a side note, you should also avoid starting an Activity from an -Intent Receiver, as it will spawn a new screen that will steal focus from -whatever application the user is currently has running. If your application -has something to show the user in response to an Intent broadcast, it should -do so using the {@link android.app.NotificationManager Notification -Manager}.
- -Generally, 100 to 200ms is the threshold beyond which users will perceive -lag (or lack of "snappiness," if you will) in an application. As such, here -are some additional tips beyond what you should do to avoid ANR that will help -make your application seem responsive to users.
- -Even if your application is fast and responsive, certain design decisions can -still cause problems for users — because of unplanned interactions with -other applications or dialogs, inadvertent loss of data, unintended blocking, -and so on. To avoid these problems, it helps to understand the context in which -your applications run and the system interactions that can affect your -application. In short, you should strive to develop an application that -interacts seamlessly with the system and with other applications.
- -A common seamlessness problem is when an application's background process -— for example, a service or broadcast receiver — pops up a dialog in -response to some event. This may seem like harmless behavior, especially when -you are building and testing your application in isolation, on the emulator. -However, when your application is run on an actual device, your application may -not have user focus at the time your background process displays the dialog. So -it could end up that your application would display it's dialog behind the -active application, or it could take focus from the current application and -display the dialog in front of whatever the user was doing (such as dialing a -phone call, for example). That behavior would not work for your application or -for the user.
- -To avoid these problems, your application should use the proper system -facility for notifying the user — the -{@link android.app.Notification Notification} classes. Using -notifications, your application can signal the user that an event has -taken place, by displaying an icon in the status bar rather than taking -focus and interrupting the user.
- -Another example of a seamlessness problem is when an activity inadvertently -loses state or user data because it doesn't correctly implement the onPause() -and other lifecycle methods. Or, if your application exposes data intended to be -used by other applications, you should expose it via a ContentProvider, rather -than (for example) doing so through a world-readable raw file or database.
- -What those examples have in common is that they involve cooperating nicely -with the system and other applications. The Android system is designed to treat -applications as a sort of federation of loosely-coupled components, rather than -chunks of black-box code. This allows you as the developer to view the entire -system as just an even-larger federation of these components. This benefits you -by allowing you to integrate cleanly and seamlessly with other applications, and -so you should design your own code to return the favor.
- -This document discusses common seamlessness problems and how to avoid them. -It covers these topics:
-Always keep in mind that Android is a mobile platform. It may seem obvious to -say it, but it's important to remember that another Activity (such as the -"Incoming Phone Call" app) can pop up over your own Activity at any moment. -This will fire the onSaveInstanceState() and onPause() methods, and will likely result in -your application being killed.
- -If the user was editing data in your application when the other Activity -appeared, your application will likely lose that data when your application is -killed. Unless, of course, you save the work in progress first. The "Android -Way" is to do just that: Android applications that accept or edit input should -override the onSaveInstanceState() method and save their state in some appropriate -fashion. When the user revisits the application, she should be able to -retrieve her data.
- -A classic example of a good use of this behavior is a mail application. If the -user was composing an email when another Activity started up, the application -should save the in-process email as a draft.
- -If you wouldn't walk down the street in your underwear, neither should your -data. While it's possible to expose certain kinds of application to the world -to read, this is usually not the best idea. Exposing raw data requires other -applications to understand your data format; if you change that format, you'll -break any other applications that aren't similarly updated.
- -The "Android Way" is to create a ContentProvider to expose your data to other -applications via a clean, well-thought-out, and maintainable API. Using a -ContentProvider is much like inserting a Java language interface to split up and -componentize two tightly-coupled pieces of code. This means you'll be able to -modify the internal format of your data without changing the interface exposed -by the ContentProvider, and this without affecting other applications.
- -If the user is running an application (such as the Phone application during a -call) it's a pretty safe bet he did it on purpose. That's why you should avoid -spawning activities except in direct response to user input from the current -Activity.
- -That is, don't call startActivity() from BroadcastReceivers or Services running in -the background. Doing so will interrupt whatever application is currently -running, and result in an annoyed user. Perhaps even worse, your Activity may -become a "keystroke bandit" and receive some of the input the user was in the -middle of providing to the previous Activity. Depending on what your -application does, this could be bad news.
- -Instead of spawning Activity UIs directly from the background, you should -instead use the NotificationManager to set Notifications. These will appear in -the status bar, and the user can then click on them at his leisure, to see -what your application has to show him.
- -(Note that all this doesn't apply to cases where your own Activity is already -in the foreground: in that case, the user expects to see your next Activity in -response to input.)
- -If your application needs to perform some expensive or long-running -computation, you should probably move it to a thread. This will prevent the -dreaded "Application Not Responding" dialog from being displayed to the user, -with the ultimate result being the fiery demise of your application.
- -By default, all code in an Activity as well as all its Views run in the same -thread. This is the same thread that also handles UI events. For example, when -the user presses a key, a key-down event is added to the Activity's main -thread's queue. The event handler system needs to dequeue and handle that -event quickly; if it doesn't, the system concludes after a few seconds that -the application is hung and offers to kill it for the user.
- -If you have long-running code, running it inline in your Activity will run it -on the event handler thread, effectively blocking the event handler. This will -delay input processing, and result in the ANR dialogs. To avoid this, move -your computations to a thread. This Design for Responsiveness document -discusses how to do that..
- -Any application worth using will probably have several different screens. -When designing the screens of your UI, be sure to make use of multiple Activity -object instances.
- -Depending on your development background, you may interpret an Activity as -similar to something like a Java Applet, in that it is the entry point for -your application. However, that's not quite accurate: where an Applet subclass -is the single entry point for a Java Applet, an Activity should be thought of -as one of potentially several entry points to your application. The only -difference between your "main" Activity and any others you might have is that -the "main" one just happens to be the only one that expressed an interest in -the "android.intent.action.MAIN" action in your AndroidManifest..xml file.
- -So, when designing your application, think of your application as a federation -of Activity objects. This will make your code a lot more maintainable in the long -run, and as a nice side effect also plays nicely with Android's application -history and "backstack" model.
- -When it comes to the look-and-feel of the user interface, it's important to -blend in nicely. Users are jarred by applications which contrast with the user -interface they've come to expect. When designing your UIs, you should try and -avoid rolling your own as much as possible. Instead, use a Theme. You -can override or extend those parts of the theme that you need to, but at least -you're starting from the same UI base as all the other applications. For all -the details, read Applying Styles and Themes.
- -Different Android-powered devices will support different screen resolutions. -Some will even be able to change resolutions on the fly, such as by switching -to landscape mode. It's important to make sure your layouts and drawables -are flexible enough to display properly on a variety of device screens.
- -Fortunately, this is very easy to do. In brief, what you must do is -provide different versions of your artwork (if you use any) for the key -resolutions, and then design your layout to accommodate various dimensions. -(For example, avoid using hard-coded positions and instead use relative -layouts.) If you do that much, the system handles the rest, and your -application looks great on any device.
- -Android devices will come with a variety of network-connectivity options. All -will have some data-access provision, though some will be faster than others. -The lowest common denominator, however, is GPRS, the non-3G data service for -GSM networks. Even 3G-capable devices will spend lots of time on non-3G -networks, so slow networks will remain a reality for quite a long time to -come.
- -That's why you should always code your applications to minimize network -accesses and bandwidth. You can't assume the network is fast, so you should -always plan for it to be slow. If your users happen to be on faster networks, -then that's great — their experience will only improve. You want to avoid the -inverse case though: applications that are usable some of the time, but -frustratingly slow the rest based on where the user is at any given moment are -likely to be unpopular.
- -One potential gotcha here is that it's very easy to fall into this trap if -you're using the emulator, since the emulator uses your desktop computer's -network connection. That's almost guaranteed to be much faster than a cell -network, so you'll want to change the settings on the emulator that simulate -slower network speeds. You can do this in Eclipse, in the "Emulator Settings" -tab of your launch configuration or via a command-line -option when starting the emulator.
- --Android will support a variety of handset form-factors. That's a fancy way of -saying that some Android devices will have full "QWERTY" keyboards, while -others will have 40-key, 12-key, or even other key configurations. Similarly, -some devices will have touch-screens, but many won't. -
-When building your applications, keep that in mind. Don't make assumptions -about specific keyboard layouts -- unless, of course, you're really interested -in restricting your application so that it can only be used on those devices. -
- --A mobile device isn't very mobile if it's constantly plugged into the -wall. Mobile devices are battery-powered, and the longer we can make that -battery last on a charge, the happier everyone is — especially the user. -Two of the biggest consumers of battery power are the processor, and the -radio; that's why it's important to write your applications to do as little -work as possible, and use the network as infrequently as possible. -
-Minimizing the amount of processor time your application uses really comes -down to writing efficient -code. To minimize the power drain from using the radio, be sure to handle -error conditions gracefully, and only fetch what you need. For example, don't -constantly retry a network operation if one failed. If it failed once, it's -likely because the user has no reception, so it's probably going to fail again -if you try right away; all you'll do is waste battery power. -
-Users are pretty smart: if your program is power-hungry, you can count on -them noticing. The only thing you can be sure of at that point is that your -program won't stay installed very long. -
diff --git a/docs/html/guide/practices/index.html b/docs/html/guide/practices/index.html deleted file mode 100644 index 4881acf..0000000 --- a/docs/html/guide/practices/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/publishing/app-signing.jd b/docs/html/guide/publishing/app-signing.jd deleted file mode 100644 index 1862b50..0000000 --- a/docs/html/guide/publishing/app-signing.jd +++ /dev/null @@ -1,489 +0,0 @@ -page.title=Signing Your Applications -@jd:body - -This document provides information about signing your Android applications prior to publishing them for mobile device users.
- -The Android system requires that all installed applications be digitally -signed with a certificate whose private key is held by the application's -developer. The system uses the certificate as a means of identifying the author of -an application and establishing trust relationships between applications, rather -than for controlling which applications the user can install. The certificate -does not need to be signed by a certificate authority: it is perfectly -allowable, and typical, for Android applications to use self-signed -certificates.
- -The important points to understand about signing Android applications are:
- -The Android system will not install or run an application that is not signed appropriately. This -applies wherever the Android system is run, whether on an actual device or on the emulator. -For this reason, you must set up signing for your application before you will be able to -run or debug it on an emulator or device.
- -The Android SDK tools assist you in signing your applications when debugging. Both the ADT Plugin -for Eclipse and the Ant build tool offer two signing modes — debug mode and release mode. - -
Some aspects of application signing may affect how you approach the development -of your application, especially if you are planning to release multiple -applications.
- -In general, the recommended strategy for all developers is to sign -all of your applications with the same certificate, throughout the expected -lifespan of your applications. There are several reasons why you should do so:
- -Another important consideration in determining your signing strategy is -how to set the validity period of the key that you will use to sign your -applications.
- -As you design your application, keep these points in mind and make sure to -use a suitable certificate to sign your applications.
- -To support the generation of a keystore and debug key, you should first make sure that -Keytool is available to the SDK build -tools. In most cases, you can tell the SDK build tools how to find Keytool by making sure -that your JAVA_HOME environment variable is set and that it references a suitable JDK. -Alternatively, you can add the JDK version of Keytool to your PATH variable.
- -If you are developing on a version of Linux that originally came with GNU Compiler for -Java, make sure that the system is using the JDK version of Keytool, rather than the gcj -version. If Keytool is already in your PATH, it might be pointing to a symlink at -/usr/bin/keytool. In this case, check the symlink target to make sure that it points -to the Keytool in the JDK.
- -If you will release your application to the public, you will also need to have -the Jarsigner tool available on your machine. Both Jarsigner and Keytool are included -in the JDK.
- -The Android build tools provide a debug signing mode that makes it easier for you -to develop and debug your application, while still meeting the Android system -requirement for signing your .apk when it is installed in the emulator or a device. -When you use debug mode, the SDK tools invoke Keytool to create a debug -keystore and key.
- -The SDK tools create the debug keystore/key with predetermined names/passwords;
-If you are developing in Eclipse/ADT and have set up Keytool as described -above, signing in debug mode is enabled by default. When you run or debug your -application, ADT signs the .apk with the debug certificate and installs it on -the emulator. No specific action on your part is needed, provided ADT has -access to Keytool.
- -If you use Ant to build your .apk files, debug signing mode -is enabled by default, assuming that you are using a build.xml file generated by the -activitycreator tool included in the latest SDK. When you run Ant against build.xml to -compile your app, the build script generates a keystore/key and signs the .apk for you. -No specific action on your part is needed.
- -If necessary, you can change the location/name of the debug keystore/key or -supply a custom debug keystore/key to use. In Eclipse/ADT, you can use -Windows > Prefs > -Android > Build. However, any custom debug -keystore/key must use the same keystore/key names and passwords as the default -debug key (as described above).
- -Note that you cannot release your application to the public if it -is signed with the debug certificate.
- -The self-signed certificate used to sign your application in debug mode (the default on -Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.
- -When the certificate expires, you will get a build error. On Ant builds, the error -looks like this:
- -debug: -[echo] Packaging bin/samples-debug.apk, and signing it with a debug key... -[exec] Debug Certificate expired on 8/4/08 3:43 PM- -
In Eclipse/ADT, you will see a similar error in the Android console.
- -To fix this problem, simply delete the debug.keystore file. On Linux/Mac OSX,
-the file is stored in ~/.android. On Windows XP, the file is stored in
-C:\Documents and Settings\<user>\Local Settings\Application Data\Android.
-On Windows Vista, the file is stored in
-C:\Users\<user>\AppData\Local\Android.
The next time you build, the build tools will regenerate a new keystore and debug key.
- -Note that, if your development machine is using a non-Gregorian locale, the build -tools may erroneously generate an already-expired debug certificate, so that you get an -error when trying to compile your application. For workaround information, see the -troubleshooting topic -I can't compile my app because the build tools generated an expired debug -certificate.
- -When your application is ready for release to other users, you must:
-The sections below provide information about these steps.
- -To prepare your application for release, you must first compile it in release mode. -In release mode, the Android build tools compile your application as usual, -but without signing it with the debug key.
- -If you are developing in Eclipse/ADT, right-click the project in the Package -pane and select Android Tools > Export Application -Package. You can then specify the file location for the unsigned .apk. -Alternatively, you can follow the "Exporting the unsigned .apk" -link in the Manifest Editor overview page.
- -If you are using Ant, all you need to do is specify the build target -"release" in the Ant command. For example, if you are running Ant from the -directory containing your build.xml file, the command would look like this:
- -$ ant release- -
The build script compiles the application .apk without signing it. - -
Note that you can not release your application unsigned, or signed with the debug key.
- -In preparation for signing your application, you must first ensure that -you have a suitable private key with which to sign. A suitable private -key is one that:
- -If you plan to publish your application(s) on Android Market, note that a -validity period ending after 22 October 2033 is a requirement. You can not upload an -application if it is signed with a key whose validity expires before that date. -
The key may be self-signed. If you do not have a suitable key, you must -generate one using Keytool. Make sure that you have Keytool available, as described -in Basic Setup.
- -To generate a self-signed key with Keytool, use the keytool
-command and pass any of the options listed below (and any others, as
-needed).
Before you run Keytool, make sure to read -Securing Your Private Key for a discussion of how to keep -your key secure and why doing so is critically important to you and to users. In -particular, when you are generating your key, you should select strong passwords -for both the keystore and key.
- -| Keytool Option | -Description | -
|---|---|
-genkey | Generate a key pair (public and private -keys) | -
-v | Enable verbose output. | -
-keystore <keystore-name>.keystore | A name -for the keystore containing the private key. | -
-storepass <password> | A password for the -keystore. As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
-alias <alias_name> | An alias for the key. | -
-keyalg <alg> | The encryption algorithm to use -when generating the key. Both DSA and RSA are supported. | -
-dname <name> | A Distinguished Name that describes -who created the key. The value is used as the issuer and subject fields in the -self-signed certificate. Note that you do not need to specify this option -in the command line. If not supplied, Jarsigner prompts you to enter each -of the Distinguished Name fields (CN, OU, and so on). |
-
-validity <valdays> | The validity period for the -key, in days. Note: A value of 10000 or greater is recommended. |
-
-keypass <password> | The password for the key. -As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
Here's an example of a Keytool command that generates a private key:
- -$ keytool -genkey -v -keystore my-release-key.keystore --alias alias_name -keyalg RSA -validity 10000- -
Running the example command above, Keytool prompts you to provide
-passwords for the keystore and key, and to provide the Distinguished
-Name fields for your key. It then generates the keystore as a file called
-my-release-key.keystore. The keystore and key are
-protected by the passwords you entered. The keystore contains
-a single key, valid for 10000 days. The alias is a name that you —
-will use later, to refer to this keystore when signing your application.
For more information about Keytool, see the documentation at - -http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security
- -When you are ready to actually sign your .apk for release, you can do so -using the Jarsigner tool. Make sure that you have Jarsigner available on your -machine, as described in Basic Setup. Also, make sure that -the keystore containing your private key is available.
- -To sign your application, you run Jarsigner, referencing both the -application's .apk and the keystore containing the private key with which to -sign the .apk. The table below shows the options you could use.
- -
| Jarsigner Option | -Description | -
|---|---|
-keystore <keystore-name>.keystore | The name of -the keystore containing your private key. | -
-verbose | Enable verbose output. | -
-storepass <password> | The password for the -keystore. As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Jarsigner prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
-keypass <password> | The password for the private -key. As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Jarsigner prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
Here's how you would use Jarsigner to sign an application package called
-my_application.apk, using the example keystore created above.
-
$ jarsigner -verbose -keystore my-release-key.keystore -my_application.apk alias_name- -
Running the example command above, Jarsigner prompts you to provide -passwords for the keystore and key. It then modifies the APK -in-place, meaning the .apk is now signed. Note that you can sign an -APK multiple times with different keys.
- -To verify that your .apk is signed, you can use a command like this:
- -$ jarsigner -verify my_signed.apk- -
If the .apk is signed properly, Jarsigner prints "jar verified". -If you want more details, you can try one of these commands:
- -$ jarsigner -verify -verbose my_application.apk- -
or
- -$ jarsigner -verify -verbose -certs my_application.apk- -
The command above, with the -certs option added, will show you the
-"CN=" line that describes who created the key.
Note: if you see "CN=Android Debug", this means the .apk was -signed with the debug key generated by the Android SDK. If you intend to release -your application, you must sign it with your private key instead of the debug -key.
- -For more information about Jarsigner, see the documentation at - -http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security
- -Maintaining the security of your private key is of critical importance, both -to you and to the user. If you allow someone to use your key, or if you leave -your keystore and passwords in an unsecured location such that a third-party -could find and use them, your authoring identity and the trust of the user -are compromised.
- -If a third party should manage to take your key without your knowledge or -permission, that person could sign and distribute applications that maliciously -replace your authentic applications or corrupt them. Such a person could also -sign and distribute applications under your identity that attack other -applications or the system itself, or corrupt or steal user data.
- -Your reputation as a developer entity depends on your securing your private -key properly, at all times, until the key is expired. Here are some tips for -keeping your key secure:
- --storepass and -keypass options at the command line.
-If you do so, your passwords will be available in your shell history,
-which any user on your computer could access.-storepass and -keypass
-options at the command line. In general, if you follow common-sense precautions when generating, using, -and storing your key, it will remain secure.
\ No newline at end of file diff --git a/docs/html/guide/publishing/preparing.jd b/docs/html/guide/publishing/preparing.jd deleted file mode 100644 index 4db546d..0000000 --- a/docs/html/guide/publishing/preparing.jd +++ /dev/null @@ -1,252 +0,0 @@ -page.title=Preparing to Publish: A Checklist -@jd:body - - - -Publishing an application means testing it, packaging it appropriately, and -making it available to users of Android-powered mobile devices.
- -If you plan to publish your application for installation on Android-powered devices, -there are several things you need to do, to get your application ready. This document -the significant checkpoints for preparing your application for a successful release.
- -If you will publish your application on Android Market, please also see Publishing on Android Market -for specific preparation requirements for your application.
- -For general information about the ways that you can publish an applications, -see the Publishing Your -Applications document.
- -Before you consider your application ready for release:
- -Before you do the final compile of your application:
- -Compile your application...
-After compiling your application:
-It's important to test your application as extensively as possible, in as -many areas as possible. To help you do that, Android provides a variety of -testing classes and tools. You can use -{@link android.app.Instrumentation Instrumentation} to run JUnit and other -test cases, and you can use testing -tools such as the UI/Application -Exerciser Monkey.
- --dpi,
--device, -scale, -netspeed,
--netdelay, -cpu-delay and others to model the
-emulator's screen, network performance, and other attributes to match the target
-device to the greatest extent possible. You can then test your application's UI
-and performance. However, we strongly recommend that you test your application
-on an actual target device before publishing it. To protect your person, organization, and intellectual property, you may want -to provide an End User License Agreement (EULA) with your application. - -
The icon and label that you specify in an application's manifest are -important because they are displayed to users as your application's icon and -name. They are displayed on the device's Home screen, as well as in Manage -Applications, My Downloads, and elsewhere. Additionally, publishing services may -display the icon and label to users.
- -To specify an icon and label, you define the attributes
-android:icon and android:label in the
-<application> element of the manifest.
As regards the design of your icon, you should try to make it match as much -as possible the style used by the built-in Android applications.
- -For release, you should make sure that debug facilities are turned off and -that debug and other unnecessary data/files are removed from your application -project.
-android:debuggable="true" attribute from the
-<application> element of the manifest.Before you compile your application, you must make sure that you have defined
-a version number for your application, specifying an appropriate value for both
-the android:versionCode and android:versionName
-attributes of the <manifest> element in the application's
-manifest file. Carefully consider your version numbering plans in the context of
-your overall application upgrade strategy.
If you have previously released a version of your application, you must make
-sure to increment the version number of the current application. You must
-increment both the android:versionCode and
-android:versionName attributes of the <manifest>
-element in the application's manifest file, using appropriate values.
For detailed information about how to define version information for your -application, see Versioning Your Applications.
- -If you have read and followed all of the preparation steps up to this point, -your application is compiled and ready for signing. Inside the .apk, the -application is properly versioned, and you've cleaned out extra files and -private data, as described above.
- -Before you sign your application, you need to make sure that you have a -suitable private key. For complete information about how to obtain (or generate) -a private key, see Obtaining a Private Key.
- -Once you have obtained (or generated) a suitable private key, you will use it -to:
- -For complete information
-about getting a Maps API Key, see Obtaining a Maps API
-Key.
If your application uses one or more -{@link-fixme com.google.android.maps.MapView Mapview} elements, you will need to -register your application with the Google -Maps service and obtain a Maps API Key, before your MapView(s) will be able to -retrieve data from Google Maps. To do so, you supply an MD5 fingerprint of your -signer certificate to the Maps service.
- -During development, you can get a temporary Maps API Key by registering the -debug key generated by the SDK tools. However, before publishing your -application, you must register for a new Maps API Key that is based on your -private key.
- -If your application uses MapView elements, the important points to understand -are:
- -android:apiKey — in your
-application's layout files. If you are instantiating MapView objects directly
-from code, you must pass the Maps API Key as a parameter in the constructor.
-For more information about signing and your private key, see Signing Your Applications.
- - -When you've prepared your application as described in the previous sections, -you can compile your application for release.
- -Sign your application using your private key. Signing your application -correctly is critically important. Please see Signing Your -Applications for complete information.
- -Before you release your compiled application, you should thoroughly test it -on the target mobile device (and target network, if possible). In particular, -you should make sure that any MapView elements in your UI are receiving maps -data properly. If they are not, go back to Register for a -Maps API Key and correct the problem. You should also ensure that the -application works correctly with any server-side services and data that you are -providing or are relying on and that the application handles any authentication -requirements correctly.
- -After testing, you are now ready to publish your application to mobile device -users.
- - diff --git a/docs/html/guide/publishing/publishing.jd b/docs/html/guide/publishing/publishing.jd deleted file mode 100644 index aed244e..0000000 --- a/docs/html/guide/publishing/publishing.jd +++ /dev/null @@ -1,250 +0,0 @@ -page.title=Publishing Your Applications -@jd:body - -
-
-Publishing an application means testing it, packaging it appropriately, and making -it available to users of Android-powered mobile devices for download or sideload.
- -If you've followed the steps outlined in -Preparing to -Publish Your Applications, the result of the process is a compiled .apk that -is signed with your release private key. Inside the .apk, the application is -properly versioned and any MapView elements reference a Maps API Key that you -obtained by registering the MD5 fingerprint of the same certificate used to sign -the .apk. Your application is now ready for publishing.
- -The sections below provide information about publishing your Android -application to mobile device users.
- -Android Market is a hosted service that makes it easy for users to find and -download Android applications to their Android-powered devices, and makes it -easy for developers to publish their applications to Android users.
- -To publish your application on Android Market, you first need to register -with the service using your Google account and agree to the terms of service. -Once you are registered, you can upload your application to the service whenever -you want, as many times as you want, and then publish it when you are ready. -Once published, users can see your application, download it, and rate it using -the Market application installed on their Android-powered devices.
- -To register as an Android Market developer and get started with publishing, -visit the Android Market:
- -http://market.android.com/publish -
- -If you plan to publish your application on Android Market, you must make sure -that it meets the requirements listed below, which are enforced by the Market -server when you upload the application.
- -Requirements enforced by the Android Market server
-android:versionCode and an
-android:versionName attribute in the <manifest>
-element of its manifest. The server uses the android:versionCode as
-the basis for identifying the application internally and handling upgrades, and
-it displays the android:versionName to users as the application's
-version.android:icon and an
-android:label attribute in the <application>
-element of its manifest.The beta version of Android Market does not support notifying your users when -you publish a new version of your application. This capability will be -added soon, but currently the user must independently initiate download of an -upgraded application. When you publish an upgrade, you can assist users by -notifying them that the upgrade is available and giving them a way to download -the upgraded application from Android Market.
- -Here is a suggested way of tracking installed application versions and -notifying users that an upgrade is available:
- -android:versionCode) and a URI string that your application
-can later send in an Intent, to launch Market and search for the
-upgraded application for the user.
-
-The URI that your web service returns should be properly formatted to -search Android Market for your upgraded application. See -Using Intents to Launch the Market Application -for more information. The URI should specify the upgraded -application's package name as the query parameter, since the package name -is guaranteed to be unique on Android Market. The URI format for the -package name search is:
- -http://market.android.com/search?q=pname:<package> or
-market://search?q=pname:<package>
Note that, because the URI string is received from your web -service and not hard-coded into your application, you can easily change -the Market launch behaviors whenever needed, without -having to change your application.
For more information about URIs you can pass to the Market application at -launch, see Using Intents to Launch the Market -Application, below.
- -Android-powered devices include a preinstalled Market application that gives -users access to the Android Market site. From Market, users can -browse or search available applications, read ratings and reviews, and -download/install applications.
- -You can launch the Market application from another Android -application by sending an Intent to the system. You might want to do -this, for example, to help the user locate and download an upgrade to an -installed application, or to let the user know about related -applications that are available for download.
- -To launch Market, you send an ACTION_VIEW Intent, passing a Market-handled -URI string as the Intent data. In most cases, your application would call -startActivity() to send the ACTION_VIEW Intent with the Market-handled URI.
- -The URI that you supply with the Intent lets the system route the intent -properly and also expresses the type of action that you want Market to perform -after launch. Currently, you can have Market initiate a search for applications -on Android Market, based on query parameters that you provide. For example, you -can specify URIs to search for applications by:
- -Note that the URI queries return results from the public metadata supplied by -developers in their Android Market profiles or application publishing -information, but not from the developer's private account or from the -certificate used to sign the application.
- -The table below provides a list of URIs and actions currently -supported by the Market application.
- -| For this Result | -Pass this URI with the ACTION_VIEW Intent | -Comments | -
|---|---|---|
| Search for an application by its fully qualified Java package name and -display the result. | -http://market.android.com/search?q=pname:<package> or- market://search?q=pname:<package> |
-Searches only the Java package name of applications. Returns only exact -matches. | -
| Search for applications by developer name and display the results. | -http://market.android.com/search?q=pub:"<Developer Name>"
-ormarket://search?q=pub:"<Developer Name>" |
-Searches only the "Developer Name" fields of Market public profiles. -Returns exact matches only. | -
| Search for applications by substring and display the results. | -http://market.android.com/search?q=<substring> or
-market://search?q=<substring> |
-Searches all public fields (application title, developer name, and -application description) for all applications. Returns exact and partial -matches. | -
| Search using multiple query parameters and display the results. | -Example:
|
-Returns a list of applications meeting all the supplied parameters. | -
Note that these URIs work only when passed as intent data — you -can't currently load the URIs in a web browser, either on a desktop machine or -on the device.
\ No newline at end of file diff --git a/docs/html/guide/publishing/versioning.jd b/docs/html/guide/publishing/versioning.jd deleted file mode 100644 index d0eafcd..0000000 --- a/docs/html/guide/publishing/versioning.jd +++ /dev/null @@ -1,155 +0,0 @@ -page.title=Versioning Your Applications -@jd:body - -Versioning is a critical component of your application upgrade/maintenance -strategy.
- -The Android system itself does not ever check the application version -information for an application, such as to enforce restrictions on upgrades, -compatibility, and so on. Instead, only users or applications themselves are -responsible for enforcing any version restrictions for applications themselves.
- -The Android system does check any system version compatibility expressed
-by an application in its manifest, in the minSdkVersion attribute. This
-allows an application to specify the minimum system API with which is compatible.
-For more information see Specifying Minimum System API Version.
-
-
To define the version information for your application, you set attributes in -the application's manifest file. Two attributes are available, and you should -always define values for both of them:
- -android:versionCode — An integer value that represents
-the version of the application code, relative to other versions.
-
-The value is an integer so that other applications can programatically -evaluate it, for example to check an upgrade or downgrade relationship. You can -set the value to any integer you want, however you should make sure that each -successive release of your application uses a greater value. The system does not -enforce this behavior, but increasing the value with successive releases is -normative.
- -Typically, you would release the first version of your application with
-versionCode set to 1, then monotonically increase the value with each release,
-regardless whether the release constitutes a major or minor release. This means
-that the android:versionCode value does not necessarily have a
-strong resemblence to the application release version that is visible to the
-user (see android:versionName, below). Applications and publishing
-services should not display this version value to users.
android:versionName — A string value that represents the
-release version of the application code, as it should be shown to users.
-The value is a string so that you can describe the application version as a -<major>.<minor>.<point> string, or as any other type of -absolute or relative version identifier.
- -As with android:versionCode, the system does not use this value
-for any internal purpose, other than to enable applications to display it to
-users. Publishing services may also extract the android:versionName
-value for display to users.
You define both of these version attributes in the
-<manifest> element of the manifest file.
Here's an example manifest that shows the android:versionCode
-and android:versionName attributes in the
-<manifest> element.
-<?xml version="1.0" encoding="utf-8"?> -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.example.package.name" - android:versionCode="2" - android:versionName="1.1"> - <application android:icon="@drawable/icon" android:label="@string/app_name"> - ... - </application> -</manifest> -- -
In this example, note that android:versionCode value indicates
-that the current .apk contains the second release of the application code, which
-corresponds to a minor follow-on release, as shown by the
-android:codeName string.
The Android framework provides an API to let applications query the system -for version information about your application. To obtain version information, -applications use the -{@link android.content.pm.PackageManager#getPackageInfo(java.lang.String, int)} -method of {@link android.content.pm.PackageManager PackageManager}.
- -If your application requires a specific minimum version of the Android -platform, you can specify that version as an API Level identifier -in the application's manifest file. Doing so ensures that your -application can only be installed on devices that -are running a compatible version of the Android system.
- -To specify the minimum system version in the manifest, use this attribute:
- -android:minSdkVersion — An integer value corresponding to
-the code version of the Android platform.
-When preparing to install an application, the system checks the value of this
-attribute and compares it to the system version. If the
-android:minSdkVersion value is greater than the system version, the
-system aborts the installation of the application.
If you do not specify this attribute in your manifest, the system assumes -that your application is compatible with all platform versions.
To specify a minimum platform version for your application, add a
-<uses-sdk> element as a child of
-<manifest>, then define the
-android:minSdkVersion as an attribute.
For more information, also see the Android System Image 1.1 Version Notes.
diff --git a/docs/html/guide/samples/index.jd b/docs/html/guide/samples/index.jd deleted file mode 100644 index 4e665fa..0000000 --- a/docs/html/guide/samples/index.jd +++ /dev/null @@ -1,23 +0,0 @@ -guide=true -page.title=Sample Code -@jd:body - - -Sometimes, the best way to learn how things are done is to just look at some code. So here - we've provided links to let you browse the source of some some simple Android applications.
- -The source code for these applications is included in the Android SDK, in this location:
- -<sdk>/samples/
You can easily add these applications as projects in your development environment, so that you -can modify them and watch them execute.
--A typical desktop operating system provides a common file system that any -application can use to store files that can be read by other -applications (perhaps with some access control settings). Android uses a -different system: On Android, all application data (including files) are -private to that application. -
- --However, Android also provides a standard way for an application to expose -its private data to other applications — through content providers. -A content provider is an -optional component of an application that exposes read/write access to the -application's data, subject to whatever restrictions it might impose. -Content providers implement a standard syntax for requesting and modifying -data, and a standard mechanism for reading the returned data. Android supplies -a number of content providers for standard data types, such as image, audio, -and video files and personal contact information. For more information on -using content providers, see a separate document, -Content Providers. -
- --Whether or not you want to export your application's data to others, -you need a way to store it. Android provides the following four mechanisms -for storing and retrieving data: Preferences, -Files, Databases, and Network. -
- - -Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive
-data types. It is typically used to store application preferences, such as a
-default greeting or a text font to be loaded whenever the application is started. Call
-{@link android.content.Context#getSharedPreferences(java.lang.String,int)
-Context.getSharedPreferences()} to read and write values. Assign a name to
-your set of preferences if you want to share them with other components in the same
-application, or use {@link android.app.Activity#getPreferences(int)
-Activity.getPreferences()} with no name to keep them private to the calling
-activity. You cannot share preferences across applications (except by using a
-content provider).
-
-Here is an example of setting user preferences for silent keypress mode for a -calculator: -
- -
-import android.app.Activity;
-import android.content.SharedPreferences;
-
-public class Calc extends Activity {
-public static final String PREFS_NAME = "MyPrefsFile";
- . . .
-
- @Override
- protected void onCreate(Bundle state){
- super.onCreate(state);
-
- . . .
-
- // Restore preferences
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- boolean silent = settings.getBoolean("silentMode", false);
- setSilent(silent);
- }
-
- @Override
- protected void onStop(){
- super.onStop();
-
- // Save user preferences. We need an Editor object to
- // make changes. All objects are from android.context.Context
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putBoolean("silentMode", mSilentMode);
-
- // Don't forget to commit your edits!!!
- editor.commit();
- }
-}
-
-
-
-You can store files directly on the mobile device or on a removable -storage medium. By default, other applications cannot access these files. -
- --To read data from a file, call {@link android.content.Context#openFileInput -Context.openFileInput()} and pass it the local name and path of the file. -It returns a standard Java {@link java.io.FileInputStream} object. To write -to a file, call {@link android.content.Context#openFileOutput -Context.openFileOutput()} with the name and path. It returns a {@link -java.io.FileOutputStream} object. Calling these methods with name and path -strings from another application will not work; you can only access local -files. -
- -
-If you have a static file to package with your application at compile time,
-you can save the file in your project in res/raw/myDataFile,
-and then open it with {@link
-android.content.res.Resources#openRawResource(int) Resources.openRawResource
-(R.raw.myDataFile)}. It returns an {@link java.io.InputStream}
-object that you can use to read from the file.
-
The Android API contains support for creating and using SQLite databases. -Each database is private to the application that creates it. -
- -
-The {@link android.database.sqlite.SQLiteDatabase} object represents a database
-and has methods for interacting with it — making queries and managing the
-data. To create the database, call {@link
-android.database.sqlite.SQLiteDatabase#create SQLiteDatabase.create()}
-and also subclass {@link android.database.sqlite.SQLiteOpenHelper}.
-
-As part of its support for the SQLite database system, Android exposes -database management functions that let you store complex collections of data -wrapped into useful objects. For example, Android defines a data type -for contact information; it consists of many fields including a first and last -name (strings), an address and phone numbers (also strings), a photo (bitmap -image), and much other information describing a person. -
- --Android ships with the sqlite3 database tool, which enables you to browse -table contents, run SQL commands, and perform other useful functions on SQLite -databases. See Examine databases -(sqlite3) to learn how to run this program. -
- -
-All databases, SQLite and others, are stored on the device in
-/data/data/package_name/databases.
-
-Discussion of how many tables to create, what fields they contain, and how -they are linked, is beyond the scope of this note, but Android does not -impose any limitations beyond the standard SQLite concepts. We do recommend -including an autoincrement value key field that can be used as a unique ID to -quickly find a record. This is not required for private data, but if you -implement a content provider, you must include such a unique ID field. See the -Content Providers -document for more information on this field and the NotePadProvider class -in the NotePad sample code for an example of creating and populating a -new database. Any databases you create will be accessible by name to any other -class in the application, but not outside the application. -
- - -You can also use the network to store and retrieve data (when it's available). -To do network operations, use the classes in the following packages:
- -{@link java.net java.net.*}{@link android.net android.net.*}Android includes support for 3D hardware acceleration. This functionality is -accessed via the OpenGL API — specifically, the OpenGL ES API.
- -OpenGL ES is a flavor of the OpenGL specification intended for embedded -devices. Versions of OpenGL ES are loosely peered to versions of the primary -OpenGL standard. Android currently supports OpenGL ES 1.0, which corresponds -to OpenGL 1.3. So, if the application you have in mind is possible with OpenGL -1.3 on a desktop system, it should be possible on Android.
- -The specific API provided by Android is similar to the J2ME JSR239 OpenGL -ES API. However, it may not be identical, so watch out for deviations.
- -Here's how to use the API at an extremely high level:
- -For an example of this usage model (based on the classic GL ColorCube), -see -com.android.samples.graphics.GLView1.java -in the ApiDemos sample code project. A slightly more sophisticated version showing how to use -it with threads can be found in -com.android.samples.graphics.GLSurfaceViewActivity.java. -
- -Writing a summary of how to actually write 3D applications using OpenGL is -beyond the scope of this text and is left as an exercise for the reader.
- -Information about OpenGL ES can be -found at http://www.khronos.org/opengles/.
- -Information specifically -about OpenGL ES 1.0 (including a detailed specification) can be found -at http://www.khronos.org/opengles/1_X/.
- -The documentation for the Android {@link javax.microedition.khronos.opengles.GL -OpenGL ES implementations} are also available.
- -Finally, note that though Android does include some basic support for -OpenGL ES 1.1, the support is not complete, and should not be relied -upon at this time.
diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd deleted file mode 100644 index 3c7f419..0000000 --- a/docs/html/guide/topics/fundamentals.jd +++ /dev/null @@ -1,1726 +0,0 @@ -page.title=Application Fundamentals -@jd:body - -
-Android applications are written in the Java programming language.
-The compiled Java code — along with any data and resource
-files required by the application — is bundled by the
-aapt
-tool into an Android package, an archive file
-marked by an {@code .apk} suffix. This file is the vehicle
-for distributing the application and installing it on mobile devices;
-it's the file users download to their devices. All the code in a
-single {@code .apk} file is considered to be one application.
-
-In many ways, each Android application lives in its own world: -
- --It's possible to arrange for two applications to share the same user ID, -in which case they will be able to see each other's files. To conserve -system resources, applications with the same ID can also arrange to run -in the same Linux process, sharing the same VM. -
- - --A central feature of Android is that one application can make use of elements -of other applications (provided those applications permit it). For example, -if your application needs to display a scrolling list of images and another -application has developed a suitable scroller and made it available to others, -you can call upon that scroller to do the work, rather than develop your own. -Your application doesn't incorporate the code of the other application or -link to it. Rather, it simply starts up that piece of the other application -when the need arises. -
- --For this to work, the system must be able to start an application process -when any part of it is needed, and instantiate the Java objects for that part. -Therefore, unlike applications on most other systems, Android applications don't -have a single entry point for everything in the application (no {@code main()} -function, for example). Rather, they have essential components that -the system can instantiate and run as needed. There are four types of components: -
- --An application might consist of just one activity or, like the text messaging -application just mentioned, it may contain several. -What the activities are, and how many there are depends, of course, on the -application and its design. Typically, one of the activities is marked -as the first one that should be presented to the user when the application is -launched. Moving from one activity to another is accomplished by having the -current activity start the next one. -
- --Each activity is given a default window to draw in. Typically, the window -fills the screen, but it might be smaller than the screen and float on top -of other windows. An activity can also make use of additional windows — -for example, a pop-up dialog that calls for a user response in the midst of -the activity, or a window that presents users with vital information when they -select a particular item on-screen. -
- --The visual content of the window is provided by a hierarchy of views — -objects derived from the base {@link android.view.View} class. Each view -controls a particular rectangular space within the window. Parent views -contain and organize the layout of their children. Leaf views (those at the -bottom of the hierarchy) draw in the rectangles they control and respond to -user actions directed at that space. Thus, views are where the activity's -interaction with the user takes place. For example, a view might display -a small image and initiate an action when the user taps that image. Android -has a number of ready-made views that you can use — including buttons, -text fields, scroll bars, menu items, check boxes, and more. -
- -
-A view hierarchy is placed within an activity's window by the
-{@link android.app.Activity#setContentView Activity.setContentView()}
-method. The content view is the View object at the root of the hierarchy.
-(See the separate User Interface
-document for more information on views and the hierarchy.)
-
-A prime example is a media player playing songs from a play list. The player -application would probably have one or more activities that allow the user to -choose songs and start playing them. However, the music playback itself would -not be handled by an activity because users will expect the music to keep -playing even after they leave the player and begin something different. -To keep the music going, the media player activity could start a service to run -in the background. The system would then keep the music playback service running -even after the activity that started it leaves the screen. -
- --It's possible to connect to (bind to) an ongoing service (and start the service -if it's not already running). While connected, you can communicate with the -service through an interface that the service exposes. For the music service, -this interface might allow users to pause, rewind, stop, and restart the playback. -
- --Like activities and the other components, services run in the main thread of -the application process. So that they won't block other components or the -user interface, they often spawn another thread for time-consuming tasks -(like music playback). See Processes and Threads, later. -
-An application can have any number of broadcast receivers to respond to any -announcements it considers important. All receivers extend the {@link -android.content.BroadcastReceiver} base class. -
- --Broadcast receivers do not display a user interface. However, they may start -an activity in response to the information they receive, or they may use -the {@link android.app.NotificationManager} to alert the user. Notifications -can get the user's attention in various ways — flashing -the backlight, vibrating the device, playing a sound, and so on. They -typically place a persistent icon in the status bar, which users can open to -get the message. -
-See the separate -Content -Providers document for more information on using content providers. -
-Whenever there's a request that should be handled by a particular component, -Android makes sure that the application process of the component is running, -starting it if necessary, and that an appropriate instance of the component -is available, creating the instance if necessary. -
- - --Content providers are activated when they're targeted by a request from a -ContentResolver. The other three components — activities, services, -and broadcast receivers — are activated by asynchronous messages -called intents. An intent is an {@link android.content.Intent} -object that holds the content of the message. For activities and services, -it names the action being requested and specifies the URI of the data to -act on, among other things. For example, it might convey a request for -an activity to present an image to the user or let the user edit some -text. For broadcast receivers, the Intent object names the action being -announced. For example, it might announce to interested parties that the -camera button has been pressed. -
- --There are separate methods for activiating each type of component: -
- -{@link android.content.Context#startActivity
-Context.startActivity()} or {@link
-android.app.Activity#startActivityForResult
-Activity.startActivityForResult()}. The responding activity can
-look at the initial intent that caused it to be launched by calling its
-{@link android.app.Activity#getIntent getIntent()} method.
-Android calls the activity's {@link
-android.app.Activity#onNewIntent onNewIntent()} method to pass
-it any subsequent intents.
-
-
-One activity often starts the next one. If it expects a result back from
-the activity it's starting, it calls {@code startActivityForResult()}
-instead of {@code startActivity()}. For example, if it starts an activity
-that lets the user pick a photo, it might expect to be returned the chosen
-photo. The result is returned in an Intent object that's passed to the
-calling activity's {@link android.app.Activity#onActivityResult
-onActivityResult()} method.
-
A service is started (or new instructions are given to an ongoing
-service) by passing an Intent object to {@link
-android.content.Context#startService Context.startService()}.
-Android calls the service's {@link android.app.Service#onStart
-onStart()} method and passes it the Intent object.
-Similarly, an intent can be passed to {@link
-android.content.Context#bindService Context.bindService()} to
-establish an ongoing connection between the calling component and a
-target service. The service receives the Intent object in
-an {@link android.app.Service#onBind onBind()} call.
-(If the service is not already running, {@code bindService()} can
-optionally start it.) For example, an activity might establish a connection
-with the music playback service mentioned earlier so that it can provide
-the user with the means (a user interface) for controlling the playback.
-The activity would call {@code bindService()} to set up that connection,
-and then call methods defined by the service to affect the playback.
-
-A later section, Remote procedure calls, has more details -about binding to a service. -
-An application can initiate a broadcast by passing an Intent object to
-methods like {@link
-android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()},
-{@link android.content.Context#sendOrderedBroadcast(Intent, String)
-Context.sendOrderedBroadcast()}, and {@link
-android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()}
-in any of their variations. Android delivers the intent to all interested
-broadcast receivers by calling their {@link
-android.content.BroadcastReceiver#onReceive onReceive()} methods.
-For more on intent messages, see the separate article, -Intents -and Intent Filters. -
- - --A content provider is active only while it's responding to a request from -a ContentResolver. And a broadcast receiver is active only while it's -responding to a broadcast message. So there's no need to explicitly shut -down these components. -
- --Activities, on the other hand, provide the user interface. They're -in a long-running conversation with the user and may remain active, -even when idle, as long as the conversation continues. Similarly, services -may also remain running for a long time. So Android has methods to shut -down activities and services in an orderly way: -
- -{@link android.app.Activity#finish finish()} method. One activity can
-shut down another activity (one it started with {@code startActivityForResult()}) by
-calling {@link android.app.Activity#finishActivity finishActivity()}.{@link android.app.Service#stopSelf stopSelf()} method, or by calling
-{@link android.content.Context#stopService Context.stopService()}.-Components might also be shut down by the system when they are no longer being -used or when Android must reclaim memory for more active components. A later -section, Component Lifecycles, discusses this -possibility and its ramifications in more detail. -
- - --Before Android can start an application component, it must learn that -the component exists. Therefore, applications declare their components -in a manifest file that's bundled into the Android package, the {@code .apk} -file that also holds the application's code, files, and resources. -
- --The manifest is a structured XML file and is always named AndroidManifest.xml -for all applications. It does a number of things in addition to declaring the -application's components, such as naming any libraries the application needs -to be linked against (besides the default Android library) and identifying -any permissions the application expects to be granted. -
- --But the principal task of the manifest is to inform Android about the application's -components. For example, an activity might be declared as follows: -
- -<?xml version="1.0" encoding="utf-8"?> -<manifest . . . > - <application . . . > - <activity android:name="com.example.project.FreneticActivity" - android:icon="@drawable/small_pic.png" - android:label="@string/freneticLabel" - . . . > - </activity> - . . . - </application> -</manifest>- -
-The {@code name} attribute of the
-<activity>
-element names the {@link android.app.Activity} subclass that implements the
-activity. The {@code icon} and {@code label} attributes point to
-resource files containing an icon and label that can be displayed
-to users to represent the activity.
-
-The other components are declared in a similar way —
-<service>
-elements for services,
-<receiver>
-elements for broadcast receivers, and
-<provider>
-elements for content providers. Activities, services, and content providers
-that are not declared in the manifest are not visible to the system and are
-consequently never run. However, broadcast receivers can either be
-declared in the manifest, or they can be created dynamically in code
-(as {@link android.content.BroadcastReceiver} objects)
-and registered with the system by calling
-{@link android.content.Context#registerReceiver Context.registerReceiver()}.
-
-For more on how to structure a manifest file for your application, see -The -AndroidManifest.xml File. -
- - --An Intent object can explicitly name a target component. If it does, -Android finds that component (based on the declarations in the manifest -file) and activates it. But if a target is not explicitly named, -Android must locate the best component to respond to the intent. -It does so by comparing the Intent object to the intent filters -of potential targets. A component's intent filters inform Android of -the kinds of intents the component is able to handle. Like other -essential information about the component, they're declared in the -manifest file. Here's an extension of the previous example that adds -two intent filters to the activity: -
- -<?xml version="1.0" encoding="utf-8"?> -<manifest . . . > - <application . . . > - <activity android:name="com.example.project.FreneticActivity" - android:icon="@drawable/small_pic.png" - android:label="@string/freneticLabel" - . . . > - <intent-filter . . . > - <action android:name="android.intent.action.MAIN" /> - <category android:name="android.intent.category.LAUNCHER" /> - </intent-filter> - <intent-filter . . . > - <action android:name="com.example.project.BOUNCE" /> - <data android:type="image/jpeg" /> - <category android:name="android.intent.category.DEFAULT" /> - </intent-filter> - </activity> - . . . - </application> -</manifest>- -
-The first filter in the example — the combination of the action -"{@code android.intent.action.MAIN}" and the category -"{@code android.intent.category.LAUNCHER}" — is a common one. -It marks the activity as one that should be represented in the -application launcher, the screen listing applications users can launch -on the device. In other words, the activity is the entry point for -the application, the initial one users would see when they choose -the application in the launcher. -
- --The second filter declares an action that the activity can perform on -a particular type of data. -
- --A component can have any number of intent filters, each one declaring a -different set of capabilities. If it doesn't have any filters, it can -be activated only by intents that explicitly name the component as the -target. -
- --For a broadcast receiver that's created and registered in code, the -intent filter is instantiated directly as an {@link android.content.IntentFilter} -object. All other filters are set up in the manifest. -
- --For more on intent filters, see a separate document, -Intents -and Intent Filters. -
- - --As noted earlier, one activity can start another, including one defined -in a different application. Suppose, for example, that you'd like -to let users display a street map of some location. There's already an -activity that can do that, so all your activity needs to do is put together -an Intent object with the required information and pass it to -{@code startActivity()}. The map viewer will display the map. When the user -hits the BACK key, your activity will reappear on screen. -
- --To the user, it will seem as if the map viewer is part of the same application -as your activity, even though it's defined in another application and runs in -that application's process. Android maintains this user experience by keeping -both activities in the same task. Simply put, a task is what the user -experiences as an "application." It's a group of related activities, arranged -in a stack. The root activity in the stack is the one that began the task -— typically, it's an activity the user selected in the application launcher. -The activity at the top of the stack is one that's currently running — -the one that is the focus for user actions. When one activity starts another, -the new activity is pushed on the stack; it becomes the running activity. -The previous activity remains in the stack. When the user presses the BACK key, -the current activity is popped from the stack, and the previous one resumes as -the running activity. -
- --The stack contains objects, so if a task has more than one instance of the same -Activity subclass open — multiple map viewers, for example — the -stack has a separate entry for each instance. Activities in the stack are never -rearranged, only pushed and popped. -
- --A task is a stack of activities, not a class or an element in the manifest file. -So there's no way to set values for a task independently of its activities. -Values for the task as a whole are set in the root activity. For example, the -next section will talk about the "affinity of a task"; that value is read from -the affinity set for the task's root activity. -
- --All the activities in a task move together as a unit. The entire task (the entire -activity stack) can be brought to the foreground or sent to the background. -Suppose, for instance, that the current task has four activities in its stack -— three under the current activity. The user presses the HOME key, goes -to the application launcher, and selects a new application (actually, a new task). -The current task goes into the background and the root activity for the new task is displayed. -Then, after a short period, the user goes back to the home screen and again selects -the previous application (the previous task). That task, with all four -activities in the stack, comes forward. When the user presses the BACK -key, the screen does not display the activity the user just left (the root -activity of the previous task). Rather, the activity on the top of the stack -is removed and the previous activity in the same task is displayed. -
- -
-The behavior just described is the default behavior for activities and tasks.
-But there are ways to modify almost all aspects of it. The association of
-activities with tasks, and the behavior of an activity within a task, is
-controlled by the interaction between flags set in the Intent object that
-started the activity and attributes set in the activity's
-<activity>
-element in the manifest. Both requester and respondent have a say in what happens.
-
-In this regard, the principal Intent flags are: - -
{@code FLAG_ACTIVITY_NEW_TASK}
-
{@code FLAG_ACTIVITY_CLEAR_TOP}
-
{@code FLAG_ACTIVITY_RESET_TASK_IF_NEEDED}
-
{@code FLAG_ACTIVITY_SINGLE_TOP}
-The principal {@code <activity>} attributes are: - -
{@code taskAffinity}
-
{@code launchMode}
-
{@code allowTaskReparenting}
-
{@code clearTaskOnLaunch}
-
{@code alwaysRetainTaskState}
-
{@code finishOnTaskLaunch}
-The following sections describe what some of these flags and attributes do, -how they interact, and what considerations should govern their use. -
- - --By default, all the activities in an application have an affinity for each -other — that is, there's a preference for them all to belong to the -same task. However, an individual affinity can be set for each activity -with the {@code taskAffinity} attribute of the {@code <activity>} element. -Activities defined in different applications can share an affinity, or activities -defined in the same application can be assigned different affinities. -The affinity comes into play in two circumstances: When the Intent object -that launches an activity contains the {@code FLAG_ACTIVITY_NEW_TASK} flag, -and when an activity has its {@code allowTaskReparenting} attribute set -to "{@code true}". -
- -{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flagallowTaskReparenting
-attribute-If an {@code .apk} file contains more than one "application" -from the user's point of view, you will probably want to assign different -affinities to the activities associated with each of them. -
- - -
-There are four different launch modes that can be assigned to an {@code
-<activity>} element's
-launchMode
-attribute:
-
"{@code standard}" (the default mode)
-
"{@code singleTop}"
-
"{@code singleTask}"
-
"{@code singleInstance}"
-The modes differ from each other on these four points: -
- -{@link android.content.Context#startActivity startActivity()})
-— unless the Intent object contains the
-{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag.
-In that case, a different task is chosen as described in the previous
-section, Affinities and new tasks.
-
--In contrast, the "{@code singleTask}" and "{@code singleInstance}" modes mark -activities that are always at the root of a task. They define a task; they're -never launched into another task. -
- -Whether there can be multiple instances of the activity. -A "{@code standard}" or "{@code singleTop}" activity can be instantiated -many times. They can belong to multiple tasks, and a given task can have -multiple instances of the same activity. -
- --In contrast, "{@code singleTask}" and "{@code singleInstance}" activities -are limited to just one instance. Since these activities are at the root -of a task, this limitation means that there is never more than a single -instance of the task on the device at one time. -
- -Whether the instance can have other activities in its task. -A "{@code singleInstance}" activity stands alone as the only activity in its -task. If it starts another activity, that activity will be launched into a -different task regardless of its launch mode — as if {@code -FLAG_ACTIVITY_NEW_TASK} was in the intent. In all other respects, the -"{@code singleInstance}" mode is identical to "{@code singleTask}".
- --The other three modes permit multiple activities to belong to the task. -A "{@code singleTask}" activity will always be the root activity of the task, -but it can start other activities that will be assigned to its -task. Instances of "{@code standard}" and "{@code singleTop}" -activities can appear anywhere in a stack. -
-For example, suppose a task's activity stack consists of root activity A with -activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent -arrives for an activity of type D. If D has the default "{@code standard}" launch -mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. -However, if D's launch mode is "{@code singleTop}", the existing instance is -expected to handle the new intent (since it's at the top of the stack) and the -stack remains A-B-C-D. -
- --If, on the other hand, the arriving intent is for an activity of type B, a new -instance of B would be launched no matter whether B's mode is "{@code standard}" -or "{@code singleTop}" (since B is not at the top of the stack), so the resulting -stack would be A-B-C-D-B. -
- --As noted above, there's never more than one instance of a "{@code singleTask}" -or "{@code singleInstance}" activity, so that instance is expected to handle -all new intents. A "{@code singleInstance}" activity is always at the top of -the stack (since it is the only activity in the task), so it is always in -position to handle the intent. However, a "{@code singleTask}" activity may -or may not have other activities above it in the stack. If it does, it is not -in position to handle the intent, and the intent is dropped. (Even though the -intent is dropped, its arrival would have caused the task to come to the -foreground, where it would remain.) -
-
-When an existing activity is asked to handle a new intent, the Intent
-object is passed to the activity in an
-{@link android.app.Activity#onNewIntent onNewIntent()} call.
-(The intent object that originally started the activity can be retrieved by
-calling {@link android.app.Activity#getIntent getIntent()}.)
-
-Note that when a new instance of an Activity is created to handle a new -intent, the user can always press the BACK key to return to the previous state -(to the previous activity). But when an existing instance of an -Activity handles a new intent, the user cannot press the BACK key to -return to what that instance was doing before the new intent arrived. -
- -
-For more on launch modes, see the description of the
-<activity>
-element.
-
-If the user leaves a task for a long time, the system clears the task of all -activities except the root activity. When the user returns to the task again, -it's as the user left it, except that only the initial activity is present. -The idea is that, after -a time, users will likely have abandoned what they were doing before and are -returning to the task to begin something new. -
- --That's the default. There are some activity attributes that can be used to -control this behavior and modify it: -
- -alwaysRetainTaskState
-attributeclearTaskOnLaunch
-attributefinishOnTaskLaunch
-attribute
-There's another way to force activities to be removed from the stack.
-If an Intent object includes the {@link
-android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_CLEAR_TOP}
-flag, and the target task already has an instance of the type of activity that
-should handle the intent in its stack, all activities above that instance
-are cleared away so that it stands at the top of the stack and can respond
-to the intent.
-If the launch mode of the designated activity is "{@code standard}", it too
-will be removed from the stack, and a new instance will be launched to handle
-the incoming intent. That's because a new instance is always created for
-a new intent when the launch mode is "{@code standard}".
-
-{@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction -with {@code FLAG_ACTIVITY_NEW_TASK}. When used together, these flags are -a way of locating an existing activity in another task and putting it in -a position where it can respond to the intent. -
- - --An activity is set up as the entry point for a task by giving it -an intent filter with "{@code android.intent.action.MAIN}" as the -specified action and "{@code android.intent.category.LAUNCHER}" as -the specified category. (There's an example of this type of filter -in the earlier Intent Filters section.) -A filter of this kind causes an icon and label for the activity to be -displayed in the application launcher, giving users a way both to -launch the task and to return to it at any time after it has been -launched. -
- --This second ability is important: Users must be able to leave a task -and then come back to it later. For this reason, the two launch modes -that mark activities as always initiating a task, "{@code singleTask}" -and "{@code singleInstance}", should be used only when the activity has -a {@code MAIN} and {@code LAUNCHER} filter. -Imagine, for example, what could happen if the filter is missing: -An intent launches a "{@code singleTask}" activity, initiating a new task, -and the user spends some time working in that task. The user then presses -the HOME key. The task is now ordered behind and obscured by the home -screen. And, because it is not represented in the application launcher, -the user has no way to return to it. -
- --A similar difficulty attends the {@code FLAG_ACTIVITY_NEW_TASK} flag. -If this flag causes an activity to -begin a new task and the user presses the HOME key to leave it, there -must be some way for the user to navigate back to it again. Some -entities (such as the notification manager) always start activities -in an external task, never as part of their own, so they always put -{@code FLAG_ACTIVITY_NEW_TASK} in the intents they pass to -{@code startActivity()}. If you have an activity that can be invoked -by an external entity that might use this flag, take care that the user -has a independent way to get back to the task that's started. -
- --For those cases where you don't want the user to be able to return -to an activity, set the {@code <activity>} element's {@code -finishOnTaskLaunch} to "{@code true}". -See Clearing the stack, earlier. -
- - --When the first of an application's components needs to be run, Android -starts a Linux process for it with a single thread of execution. By default, -all components of the application run in that process and thread. -
- --However, you can arrange for components to run in other processes, and you -can spawn additional threads for any process. -
- - --The process where a component runs is controlled by the manifest file. -The component elements — {@code <activity>}, -{@code <service>}, {@code <receiver>}, and {@code <provider>} -— each have a {@code process} attribute that can specify a process -where that component should run. These attributes can be set so that each -component runs in its own process, or so that some components share a process -while others do not. They can also be set so that components of -different applications run in the same process — provided that the -applications share the same Linux user ID and are signed by the same authorities. -The {@code <application>} element also has a {@code process} attribute, -for setting a default value that applies to all components. -
- -
-All components are instantiated in the main thread of the specified
-process, and system calls to the component are dispatched from that
-thread. Separate threads are not created for each instance. Consequently,
-methods that respond to those calls — methods like
-{@link android.view.View#onKeyDown View.onKeyDown()} that report
-user actions and the lifecycle notifications discussed later in the
-Component Lifecycles section — always run in the
-main thread of the process. This means
-that no component should perform long or blocking operations (such as networking
-operations or computation loops) when called by the system, since this will block
-any other components also in the process. You can spawn separate threads for
-long operations, as discussed under Threads, next.
-
-Android may decide to shut down a process at some point, when memory is -low and required by other processes that are more immediately serving -the user. Application components running in the process are consequently -destroyed. A process is restarted for those components when there's again -work for them to do. -
- --When deciding which processes to terminate, Android weighs their relative -importance to the user. For example, it more readily shuts down a process -with activities that are no longer visible on screen than a process with -visible activities. -The decision whether to terminate a process, therefore, depends on the state -of the components running in that process. Those states are the subject of -a later section, Component Lifecycles. -
- - --Even though you may confine your application to a single process, there will -likely be times when you will need to spawn a thread to do some background -work. Since the user interface must always be quick to respond to user actions, -the thread that hosts an activity should not also host time-consuming operations -like network downloads. Anything that may not be completed quickly should be -assigned to a different thread. -
- --Threads are created in code using standard Java {@link java.lang.Thread} -objects. Android provides a number of convenience classes for managing -threads — {@link android.os.Looper} for running a message loop within -a thread, {@link android.os.Handler} for processing messages, and -{@link android.os.HandlerThread} for setting up a thread with a message loop. -
- - --Android has a lightweight mechanism for remote procedure calls (RPCs) -— where a method is called locally, but executed remotely (in another -process), with any result returned back to the caller. -This entails decomposing the method call and all its attendant data to a -level the operating system can understand, transmitting it from the local -process and address space to the remote process and address space, and -reassembling and reenacting the call there. Return values have to be -transmitted in the opposite direction. Android provides all the code -to do that work, so that you can concentrate on defining and implementing -the RPC interface itself. -
- --An RPC interface can include only methods. -All methods are executed synchronously (the local method blocks until the -remote method finishes), even if there is no return value. -
- -
-In brief, the mechanism works as follows: You'd begin by declaring the
-RPC interface you want to implement using a simple IDL (interface definition
-language). From that declaration, the
-aidl
-tool generates a Java interface definition that must be made available to
-both the local and the remote process. It contains two inner class, as shown
-in the following diagram:
-
-
-
-The inner classes have all the code needed to administer remote procedure -calls for the interface you declared with the IDL. -Both inner classes implement the {@link android.os.IBinder} -interface. One of them is used locally and internally by the system; -the code you write can ignore it. -The other, called Stub, extends the {@link android.os.Binder} -class. In addition to internal code for effectuating the IPC calls, it -contains declarations for the methods in the RPC interface you declared. -You would subclass Stub to implement those methods, as indicated in the -diagram. -
- --Typically, the remote process would be managed by a service (because a -service can inform the system about the process and its connections to -other processes). It would have both the interface file generated by -the {@code aidl} tool and the Stub subclass implementing the -RPC methods. Clients of the service would have only the interface file -generated by the {@code aidl} tool. -
- --Here's how a connection between a service and its clients is set up: -
- -{@link android.content.ServiceConnection#onServiceConnected
-onServiceConnected()} and
-{@link android.content.ServiceConnection#onServiceDisconnected
-onServiceDisconnected()} methods so they can be notified
-when a successful connection to the remote service is established, and
-when it goes away. They would then call
-{@link android.content.Context#bindService bindService()}
-to set up the connection.
-{@link android.app.Service#onBind onBind()}
-method would be implemented to either accept or reject the connection,
-depending on the intent it receives (the intent passed to
-{@code bindService()}). If the connection is accepted, it returns
-an instance of the Stub subclass.
--This brief description omits some details of the RPC mechanism. For more -information, see -Designing a Remote -Interface Using AIDL and the {@link android.os.IBinder IBinder} class -description. -
- - --In a few contexts, the methods you implement may be called from more -than one thread, and therefore must be written to be thread-safe. -
- --This is primarily true for methods that can be called remotely — -as in the RPC mechanism discussed in the previous section. -When a call on a method implemented in an IBinder object originates -in the same process as the IBinder, the method is executed in the -caller's thread. However, when the call originates in another process, -the method is executed in a thread chosen from a pool of threads that -Android maintains in the same process as the IBinder; it's not executed -in the main thread of the process. For example, whereas a service's -{@code onBind()} method would be called from the main thread of the -service's process, methods implemented in the object that {@code onBind()} -returns (for example, a Stub subclass that implements RPC methods) would -be called from threads in the pool. -Since services can have more than one client, more than one pool thread -can engage the same IBinder method at the same time. IBinder methods -must, therefore, be implemented to be thread-safe. -
- -
-Similarly, a content provider can receive data requests that originate in
-other processes. Although the ContentResolver and ContentProvider classes
-hide the details of how the interprocess communication is managed,
-ContentProvider methods that respond to those requests — the methods
-{@link android.content.ContentProvider#query query()},
-{@link android.content.ContentProvider#insert insert()},
-{@link android.content.ContentProvider#delete delete()},
-{@link android.content.ContentProvider#update update()}, and
-{@link android.content.ContentProvider#getType getType()}
-— are called from a pool of threads in the content provider's
-process, not the main thread of the process. Since these methods
-may be called from any number of threads at the same time, they too must
-be implemented to be thread-safe.
-
-Application components have a lifecycle — a beginning when -Android instantiates them to respond to intents through to an end when -the instances are destroyed. In between, they may sometimes be active -or inactive,or, in the case of activities, visible to the user or -invisible. This section discusses the lifecycles of activities, -services, and broadcast receivers — including the states that they -can be in during their lifetimes, the methods that notify you of transitions -between states, and the effect of those states on the possibility that -the process hosting them might be terminated and the instances destroyed. -
- - -An activity has essentially three states:
- -It is paused if it has lost focus but is still visible to the user. -That is, another activity lies on top of it and that activity either is transparent -or doesn't cover the full screen, so some of the paused activity can show through. -A paused activity is completely alive (it maintains all state and member information -and remains attached to the window manager), but can be killed by the system in -extreme low memory situations.
It is stopped if it is completely obscured by another activity. -It still retains all state and member information. However, it is no longer -visible to the user so its window is hidden and it will often be killed by the -system when memory is needed elsewhere.
-If an activity is paused or stopped, the system can drop it from memory either -by asking it to finish (calling its {@link android.app.Activity#finish finish()} -method), or simply killing its process. When it is displayed again -to the user, it must be completely restarted and restored to its previous state. -
- --As an activity transitions from state to state, it is notified of the change -by calls to the following protected methods: -
- -{@code void onCreate(Bundle savedInstanceState)}
-
{@code void onStart()}
-
{@code void onRestart()}
-
{@code void onResume()}
-
{@code void onPause()}
-
{@code void onStop()}
-
{@code void onDestroy()}
-All of these methods are hooks that you can override to do appropriate work
-when the state changes. All activities must implement
-{@link android.app.Activity#onCreate onCreate()} to do the
-initial setup when the object is first instantiated.
-Many will also implement {@link android.app.Activity#onPause onPause()}
-to commit data changes and otherwise prepare to stop interacting with the user.
-
-An implementation of any activity lifecycle method should always first -call the superclass version. For example: -
- -protected void onPause() {
- super.onPause();
- . . .
-}
--Taken together, these seven methods define the entire lifecycle of an -activity. There are three nested loops that you can monitor by -implementing them: -
- -{@link android.app.Activity#onCreate onCreate()} through to a
-single final call to {@link android.app.Activity#onDestroy}.
-An activity does all its initial setup of "global" state in {@code onCreate()},
-and releases all remaining resources in {@code onDestroy()}. For example,
-if it has a thread running in the background to download data from the network,
-it may create that thread in {@code onCreate()} and then stop the thread in
-{@code onDestroy()}.The visible lifetime of an activity happens between a call to
-{@link android.app.Activity#onStart onStart()} until a
-corresponding call to {@link android.app.Activity#onStop onStop()}.
-During this time, the user can see the activity on-screen, though it may not
-be in the foreground and interacting with the user. Between these two methods,
-you can maintain resources that are needed to show the activity to the user.
-For example, you can register a {@link android.content.BroadcastReceiver} in
-{@code onStart()} to monitor for changes that impact your UI, and unregister
-it in {@code onStop()} when the user can no longer see what you are displaying.
-The {@code onStart()} and {@code onStop()} methods can be called multiple times,
-as the activity alternates between being visible and hidden to the user.
The foreground lifetime of an activity happens between a call
-to {@link android.app.Activity#onResume onResume()} until a
-corresponding call to {@link android.app.Activity#onPause onPause()}.
-During this time, the activity is in front of all other activities on screen and
-is interacting with the user. An activity can frequently transition between the
-resumed and paused states — for example, {@code onPause()} is called when
-the device goes to sleep or when a new activity is started, {@code onResume()}
-is called when an activity result or a new intent is delivered. Therefore, the
-code in these two methods should be fairly lightweight.
-The following diagram illustrates these loops and the paths an activity -may take between states. The colored ovals are major states the activity -can be in. The square rectangles represent the callback methods you can implement -to perform operations when the activity transitions between states. -
- -

-The following table describes each of these methods in more detail and -locates it within the activity's overall lifecycle: -
- -| Method | Description | Killable? | Next | ||
|---|---|---|---|---|---|
{@link android.app.Activity#onCreate onCreate()} |
- Called when the activity is first created.
- This is where you should do all of your normal static set up —
- create views, bind data to lists, and so on. This method is passed
- a Bundle object containing the activity's previous state, if that
- state was captured (see Saving Activity State,
- later).
- Always followed by {@code onStart()}. |
- No | -{@code onStart()} | -||
| - | {@link android.app.Activity#onRestart
-onRestart()} |
- Called after the activity has been stopped, just prior to it being
- started again.
- Always followed by {@code onStart()} |
- No | -{@code onStart()} | -|
{@link android.app.Activity#onStart onStart()} |
- Called just before the activity becomes visible to the user.
- Followed by {@code onResume()} if the activity comes - to the foreground, or {@code onStop()} if it becomes hidden. |
- No | -{@code onResume()} or {@code onStop()} |
-||
| - | {@link android.app.Activity#onResume onResume()} |
- Called just before the activity starts
- interacting with the user. At this point the activity is at
- the top of the activity stack, with user input going to it.
- Always followed by {@code onPause()}. |
- No | -{@code onPause()} | -|
{@link android.app.Activity#onPause onPause()} |
- Called when the system is about to start resuming another
- activity. This method is typically used to commit unsaved changes to
- persistent data, stop animations and other things that may be consuming
- CPU, and so on. It should do whatever it does very quickly, because
- the next activity will not be resumed until it returns.
- Followed either by {@code onResume()} if the activity - returns back to the front, or by {@code onStop()} if it becomes - invisible to the user. |
- Yes | -{@code onResume()} or {@code onStop()} |
-||
{@link android.app.Activity#onStop onStop()} |
- Called when the activity is no longer visible to the user. This
- may happen because it is being destroyed, or because another activity
- (either an existing one or a new one) has been resumed and is covering it.
- Followed either by {@code onRestart()} if - the activity is coming back to interact with the user, or by - {@code onDestroy()} if this activity is going away. |
- Yes | -{@code onRestart()} or {@code onDestroy()} |
-||
{@link android.app.Activity#onDestroy
-onDestroy()} |
- Called before the activity is destroyed. This is the final call
- that the activity will receive. It could be called either because the
- activity is finishing (someone called {@link android.app.Activity#finish
- finish()} on it), or because the system is temporarily destroying this
- instance of the activity to save space. You can distinguish
- between these two scenarios with the {@link
- android.app.Activity#isFinishing isFinishing()} method. |
- Yes | -nothing | -||
-Note the Killable column in the table above. It indicates -whether or not the system can kill the process hosting the activity -at any time after the method returns, without executing another -line of the activity's code. Three methods ({@code onPause()}, -{@code onStop()}, and {@code onDestroy()}) are marked "Yes." Because -{@code onPause()} is the first of the three, it's the only one that's -guaranteed to be called before the process is killed — -{@code onStop()} and {@code onDestroy()} may not be. Therefore, you -should use {@code onPause()} to write any persistent data (such as user -edits) to storage. -
- --Methods that are marked "No" in the Killable column protect the -process hosting the activity from being killed from the moment they are -called. Thus an activity is in a killable state, for example, from the -time {@code onPause()} returns to the time {@code onResume()} is called. -It will not again be killable until {@code onPause()} again returns. -
- --As noted in a later section, Processes and lifecycle, -an activity that's not technically "killable" by this definition might -still be killed by the system — but that would happen only in -extreme and dire circumstances when there is no other recourse. -
- - --When the system, rather than the user, shuts down an activity to conserve -memory, the user may expect to return to the activity and find it in its -previous state. -
- -
-To capture that state before the activity is killed, you can implement
-an {@link android.app.Activity#onSaveInstanceState
-onSaveInstanceState()} method for the activity. Android calls this
-method before making the activity vulnerable to being destroyed —
-that is, before {@code onPause()} is called. It
-passes the method a {@link android.os.Bundle} object where you can record
-the dynamic state of the activity as name-value pairs. When the activity is
-again started, the Bundle is passed both to {@code onCreate()} and to a
-method that's called after {@code onStart()}, {@link
-android.app.Activity#onRestoreInstanceState onRestoreInstanceState()},
-so that either or both of them can recreate the captured state.
-
-Unlike {@code onPause()} and the other methods discussed earlier, -{@code onSaveInstanceState()} and {@code onRestoreInstanceState()} are -not lifecycle methods. They are not always called. For example, Android -calls {@code onSaveInstanceState()} before the activity becomes -vulnerable to being destroyed by the system, but does not bother -calling it when the instance is actually being destroyed by a user action -(such as pressing the BACK key). In that case, the user won't expect to -return to the activity, so there's no reason to save its state. -
- --Because {@code onSaveInstanceState()} is not always called, you should -use it only to record the transient state of the activity, not to store -persistent data. Use {@code onPause()} for that purpose instead. -
- - --When one activity starts another, they both experience lifecycle -transitions. One pauses and may stop, while the other starts up. -On occasion, you may need to coordinate these activities, one with -the other. -
- --The order of lifecycle callbacks is well defined, -particularly when the two activities are in the same process: -
- --A service can be used in two ways: -
- -{@link android.content.Context#startService Context.startService()}
-and stopped by calling
-{@link android.content.Context#stopService Context.stopService()}.
-It can stop itself by calling
-{@link android.app.Service#stopSelf() Service.stopSelf()} or
-{@link android.app.Service#stopSelfResult Service.stopSelfResult()}.
-Only one {@code stopService()} call is needed to stop the service, no matter how
-many times {@code startService()} was called.It can be operated programmatically using an interface that
-it defines and exports. Clients establish a connection to the Service
-object and use that connection to call into the service. The connection is
-established by calling
-{@link android.content.Context#bindService Context.bindService()},
-and is closed by calling
-{@link android.content.Context#unbindService Context.unbindService()}.
-Multiple clients can bind to the same service.
-If the service has not already been launched, {@code bindService()} can optionally
-launch it.
-
-The two modes are not entirely separate. You can bind to a service that -was started with {@code startService()}. For example, a background music -service could be started by calling {@code startService()} with an Intent -object that identifies the music to play. Only later, possibly when the -user wants to exercise some control over the player or get information -about the current song, would an activity -establish a connection to the service by calling {@code bindService()}. -In cases like this, {@code stopService()} -will not actually stop the service until the last binding is closed. -
- --Like an activity, a service has lifecycle methods that you can implement -to monitor changes in its state. But they are fewer than the activity -methods — only three — and they are public, not protected: -
- -{@code void onCreate()}
-
{@code void onStart(Intent intent)}
-
{@code void onDestroy()}
-By implementing these methods, you can monitor two nested loops of the -service's lifecycle: -
- -{@link android.app.Service#onCreate onCreate()} is called and
-the time {@link android.app.Service#onDestroy} returns.
-Like an activity, a service does its initial setup in {@code onCreate()},
-and releases all remaining resources in {@code onDestroy()}. For example,
-a music playback service could create the thread where the music will be played
-in {@code onCreate()}, and then stop the thread in {@code onDestroy()}.The active lifetime of a service begins with a call to
-{@link android.app.Service#onStart onStart()}. This method
-is handed the Intent object that was passed to {@code startService()}.
-The music service would open the Intent to discover which music to
-play, and begin the playback.
-There's no equivalent callback for when the service stops — no -{@code onStop()} method. -
-The {@code onCreate()} and {@code onDestroy()} methods are called for all
-services, whether they're started by
-{@link android.content.Context#startService Context.startService()}
-or
-{@link android.content.Context#bindService Context.bindService()}.
-However, {@code onStart()} is called only for services started by {@code
-startService()}.
-
-If a service permits others to -bind to it, there are additional callback methods for it to implement: -
- -{@code IBinder onBind(Intent intent)}
-
{@code boolean onUnbind(Intent intent)}
-
{@code void onRebind(Intent intent)}
-The {@link android.app.Service#onBind onBind()} callback is passed
-the Intent object that was passed to {@code bindService} and
-{@link android.app.Service#onUnbind onUnbind()} is handed
-the intent that was passed to {@code unbindService()}.
-If the service permits the binding, {@code onBind()}
-returns the communications channel that clients use to interact with the service.
-The {@code onUnbind()} method can ask for
-{@link android.app.Service#onRebind onRebind()}
-to be called if a new client connects to the service.
-
-The following diagram illustrates the callback methods for a service. -Although, it separates services that are created via {@code startService} -from those created by {@code bindService()}, keep in mind that any service, -no matter how it's started, can potentially allow clients to bind to it, -so any service may receive {@code onBind()} and {@code onUnbind()} calls. -
- -
-A broadcast receiver has single callback method: -
- -{@code void onReceive(Context curContext, Intent broadcastMsg)}
- -
-When a broadcast message arrives for the receiver, Android calls its
-{@link android.content.BroadcastReceiver#onReceive onReceive()}
-method and passes it the Intent object containing the message. The broadcast
-receiver is considered to be active only while it is executing this method.
-When {@code onReceive()} returns, it is inactive.
-
-A process with an active broadcast receiver is protected from being killed. -But a process with only inactive components can be killed by the system at -any time, when the memory it consumes is needed by other processes. -
- --This presents a problem when the response to a broadcast message is time -consuming and, therefore, something that should be done in a separate thread, -away from the main thread where other components of the user interface run. -If {@code onReceive()} spawns the thread and then returns, the entire process, -including the new thread, is judged to be inactive (unless other application -components are active in the process), putting it in jeopardy of being killed. -The solution to this problem is for {@code onReceive()} to start a service -and let the service do the job, so the -system knows that there is still active work being done in the process. -
- --The next section has more on the vulnerability of processes to being killed. -
- - -The Android system tries to maintain an application process for as -long as possible, but eventually it will need to remove old processes when -memory runs low. To determine which processes to keep and which to kill, -Android places each process into an "importance hierarchy" based on the -components running in it and the state of those components. Processes -with the lowest importance are eliminated first, then those with the next -lowest, and so on. There are five levels in the hierarchy. The following -list presents them in order of importance: -
- -{@link android.app.Activity#onResume
-onResume()} method has been called).It hosts a service that's bound -to the activity that the user is interacting with.
It has a {@link android.app.Service} object that's executing
-one of its lifecycle callbacks ({@link android.app.Service#onCreate
-onCreate()}, {@link android.app.Service#onStart onStart()},
-or {@link android.app.Service#onDestroy onDestroy()}).
It has a {@link android.content.BroadcastReceiver} object that's
-executing its {@link android.content.BroadcastReceiver#onReceive
-onReceive()} method.
-Only a few foreground processes will exist at any given time. They -are killed only as a last resort — if memory is so low that -they cannot all continue to run. Generally, at that point, the device has -reached a memory paging state, so killing some foreground processes is -required to keep the user interface responsive. -
A visible process is one that doesn't have any foreground -components, but still can affect what the user sees on screen. -A process is considered to be visible if either of the following conditions -holds:
- -{@link android.app.Activity#onPause onPause()}
-method has been called). This may occur, for example, if the foreground
-activity is a dialog that allows the previous activity to be seen behind it.It hosts a service that's bound to a visible activity.
-A visible process is considered extremely important and will not be killed -unless doing so is required to keep all foreground processes running. -
A service process is one that is running a service that
-has been started with the
-{@link android.content.Context#startService startService()}
-method and that does not fall into either of the two higher categories.
-Although service processes are not directly tied to anything the
-user sees, they are generally doing things that the user cares about (such
-as playing an mp3 in the background or downloading data on the network),
-so the system keeps them running unless there's not enough
-memory to retain them along with all foreground and visible processes.
-
A background process is one holding an activity
-that's not currently visible to the user (the Activity object's
-{@link android.app.Activity#onStop onStop()} method has been called).
-These processes have no direct impact on the user experience, and can be killed
-at any time to reclaim memory for a foreground, visible, or service process.
-Usually there are many background processes running, so they are kept in an
-LRU (least recently used) list to ensure that the process with the activity that
-was most recently seen by the user is the last to be killed.
-If an activity implements its lifecycle methods correctly, and captures its current
-state, killing its process will not have a deleterious effect on the user experience.
-
An empty process is one that doesn't hold any active application -components. The only reason to keep such a process around is as a cache to -improve startup time the next time a component needs to run in it. The system -often kills these processes in order to balance overall system resources between -process caches and the underlying kernel caches.
-Android ranks a process at the highest level it can, based upon the -importance of the components currently active in the process. For example, -if a process hosts a service and a visible activity, the process will be -ranked as a visible process, not a service process. -
- --In addition, a process's ranking may be increased because other processes are -dependent on it. A process that is serving another process can never be -ranked lower than the process it is serving. For example, if a content -provider in process A is serving a client in process B, or if a service in -process A is bound to a component in process B, process A will always be -considered at least as important as process B. -
- --Because a process running a service is ranked higher than one with background -activities, an activity that initiates a long-running operation might do -well to start a service for that operation, rather than simply spawn a thread -— particularly if the operation will likely outlast the activity. -Examples of this are playing music in the background -and uploading a picture taken by the camera to a web site. Using a service -guarantees that the operation will have at least "service process" priority, -regardless of what happens to the activity. As noted in the -Broadcast receiver lifecycle section earlier, this -is the same reason that broadcast receivers should employ services rather -than simply put time-consuming operations in a thread. -
diff --git a/docs/html/guide/topics/geo/lbs.jd b/docs/html/guide/topics/geo/lbs.jd deleted file mode 100644 index 981f6fe..0000000 --- a/docs/html/guide/topics/geo/lbs.jd +++ /dev/null @@ -1,73 +0,0 @@ -page.title=Location-based Service APIs -@jd:body - -The Android SDK includes two packages that provide Android's primary support -for building location-based services: -{@link android.location} and com.google.android.maps. -Please read on below for a brief introduction to each package.
- -This package contains several classes related to -location services in the Android platform. Most importantly, it introduces the -{@link android.location.LocationManager} -service, which provides an API to determine location and bearing if the -underlying device (if it supports the service). The LocationManager -should not be -instantiated directly; rather, a handle to it should be retrieved via -{@link android.content.Context#getSystemService(String) -getSystemService(Context.LOCATION_SERVICE)}.
- -Once your application has a handle to the LocationManager, your application -will be able to do three things:
- -However, during initial development, you may not have access to real -data from a real location provider (Network or GPS). So it may be necessary to -spoof some data for your application, with some mock location data.
- -Note: If you've used mock LocationProviders in -previous versions of the SDK (m3/m5), you can no longer provide canned LocationProviders -in the /system/etc/location directory. These directories will be wiped during boot-up. -Please follow the new procedures below.
- - -When testing your application on the Android emulator, there are a couple different -ways to send it some spoof location data: with the DDMS tool or the "geo" command.
- -With the DDMS tool, you can simulate location data a few different ways:
-For more information on using DDMS to spoof location data, see the -Using DDMS guide. - -
Launch your application in the Android emulator and open a terminal/console in
-your SDK's /tools directory. Now you can use:
geo fix to send a fixed geo-location.
- This command accepts a longitude and latitude in decimal degrees, and - an optional altitude in meters. For example:
-geo fix -121.45356 46.51119 4392-
geo nmea to send an NMEA 0183 sentence.
- This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit data). - For example:
-geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62-
MapView is a very useful class that lets you easily integrate Google Maps into your application. It provides built-in map downloading, rendering, and caching, as well as a variety of display options and controls. It provides a wrapper around the Google Maps API that lets your application request and manipulate Google Maps data through class methods, and it lets you work with Maps data as you would other types of Views.
- -Because MapView gives you access to Google Maps data, you need to register your application with the Google Maps service and agree to the applicable Terms of Service, before your MapView will be able to obtain data from Google Maps. This will apply whether you are developing your application on the emulator or preparing your application for deployment to mobile devices.
- -Registering your application is simple, and has two parts:
- -android:apiKey. You can use the same Maps API Key for any MapView in any application, provided that the application's .apk is signed with the certificate whose fingerprint you registered with the service. Once you have registered your application as described above, your MapView will be able to retrieve data from the Google Maps servers.
- -The MapView registration service is not yet active and Google Maps is not yet enforcing the Maps API Key requirement. The registration service will be activated soon, so that MapViews in any application deployed to a mobile device will require registration and a valid Maps API Key.
- -As soon as the registration service becomes available, this page (http://code.google.com/android/toolbox/apis/mapkey.html) will be updated with details about how and where to register and how to add your Maps API Key to your application.
- -In the meantime, you can continue developing your MapView without registration, provided that you:
-apikey parameter of the MapView constructor, if creating the MapView programmatically. When the Maps API Key checking is activated in the service, any MapViews that do not have a properly registered apiKey will stop working. The map data (tile images) of the MapView will never load (even if the device is on the network). In this case, go to the page linked above and read about how to register your certificate fingerprint and obtain a Maps API Key.
diff --git a/docs/html/guide/topics/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd deleted file mode 100644 index a72962e..0000000 --- a/docs/html/guide/topics/graphics/2d-graphics.jd +++ /dev/null @@ -1,480 +0,0 @@ -page.title=2D Graphics -parent.title=2D and 3D Graphics -parent.link=index.html -@jd:body - - -Android offers a custom 2D graphics library for drawing and animating shapes and images. -The {@link android.graphics.drawable} and {@link android.view.animation} -packages are where you'll find the common classes used for drawing and animating in two-dimensions. -
- -This document offers an introduction to drawing graphics in your Android application. -We'll discuss the basics of using Drawable objects to draw -graphics, how to use a couple subclasses of the Drawable class, and how to -create animations that either tween (move, stretch, rotate) a single graphic -or animate a series of graphics (like a roll of film).
- - -A {@link android.graphics.drawable.Drawable} is a general abstraction for "something that can be drawn." -You'll discover that the Drawable class extends to define a variety of specific kinds of drawable graphics, -including {@link android.graphics.drawable.BitmapDrawable}, {@link android.graphics.drawable.ShapeDrawable}, -{@link android.graphics.drawable.PictureDrawable}, {@link android.graphics.drawable.LayerDrawable}, and several more. -Of course, you can also extend these to define your own custom Drawable objects that behave in unique ways.
- -There are three ways to define and instantiate a Drawable: using an image saved in your project resouces; -using an XML file that defines the Drawable properties; or using the normal class constructors. Below, we'll discuss -each the first two techniques (using constructors is nothing new for an experienced developer).
- - -A simple way to add graphics to your application is by referencing an image file from your project resources. -Supported file types are PNG (preferred), JPG (acceptable) and GIF (discouraged). This technique would -obviously be preferred for application icons, logos, or other graphics such as those used in a game.
- -To use an image resource, just add your file to the res/drawable/ directory of your project.
-From there, you can reference it from your code or your XML layout.
-Either way, it is referred using a resource ID, which is the file name without the file type
-extension (E.g., my_image.png is referenced as my_image).
The following code snippet demonstrates how to build an {@link android.widget.ImageView} that uses an image -from drawable resources and add it to the layout.
-
-LinearLayout mLinearLayout;
-
-protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- // Create a LinearLayout in which to add the ImageView
- mLinearLayout = new LinearLayout(this);
-
- // Instantiate an ImageView and define its properties
- ImageView i = new ImageView(this);
- i.setImageResource(R.drawable.my_image);
- i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions
- i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
-
- // Add the ImageView to the layout and set the layout as the content view
- mLinearLayout.addView(i);
- setContentView(mLinearLayout);
-}
-
-In other cases, you may want to handle your image resource as a -{@link android.graphics.drawable.Drawable} object. -To do so, create a Drawable from the resource like so: -
Drawable myImage = Resources.getDrawable(R.drawable.my_image);- -
Caution: Each unique resource in your project can maintain only one -state, no matter how many different objects you may instantiate for it. For example, if you instantiate two -Drawable objects from the same image resource, then change a property (such as the alpha) for one of the -Drawables, then it will also affect the other. So when dealing with multiple instances of an image resource, -instead of directly transforming the Drawable, you should perform a tween animation.
- - -The XML snippet below shows how to add a resource Drawable to an -{@link android.widget.ImageView} in the XML layout (with some red tint just for fun). -
-<ImageView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:tint="#55ff0000" - android:src="@drawable/my_image"/> --
For more information on using project resources, read about - Resources and Assets.
- - -By now, you should be familiar with Android's principles of developing a -User Interface. Hence, you understand the power -and flexibility inherent in defining objects in XML. This philosophy caries over from Views to Drawables. -If there is a Drawable object that you'd like to create, which is not initially dependent on variables defined by -your applicaton code or user interaction, then defining the Drawable in XML is a good option. -Even if you expect your Drawable to change its properties during the user's experience with your application, -you should consider defining the object in XML, as you can always modify properties once it is instantiated.
- -Once you've defined your Drawable in XML, save the file in the res/drawable/ directory of
-your project. Then, retrieve and instantiate the object by calling
-{@link android.content.res.Resources#getDrawable(int) Resources.getDrawable()}, passing it the resource ID
-of your XML file. (See the example below.)
Any Drawable subclass that supports the inflate() method can be defined in
-XML and instantiated by your application.
-Each Drawable that supports XML inflation utilizes specific XML attributes that help define the object
-properties (see the class reference to see what these are). See the class documentation for each
-Drawable subclass for information on how to define it in XML.
-
-
Here's some XML that defines a TransitionDrawable:
--<transition xmlns:android="http://schemas.android.com/apk/res/android"> - <item android:drawable="@drawable/image_expand"> - <item android:drawable="@drawable/image_collapse"> -</transition> -- -
With this XML saved in the file res/drawable/expand_collapse.xml,
-the following code will instantiate the TransitionDrawable and set it as the content of an ImageView:
-Resources res = mContext.getResources(); -TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse); -ImageView image = (ImageView) findViewById(R.id.toggle_image); -image.setImageDrawable(transition); --
Then this transition can be run forward (for 1 second) with:
-transition.startTransition(1000);- -
Refer to the Drawable classes listed above for more information on the XML attributes supported by each.
- - - -When you want to dynamically draw some two-dimensional graphics, a {@link android.graphics.drawable.ShapeDrawable} -object will probably suit your needs. With a ShapeDrawable, you can programmatically draw -primitive shapes and style them in any way imaginable.
- -A ShapeDrawable is an extension of {@link android.graphics.drawable.Drawable}, so you can use one where ever
-a Drawable is expected — perhaps for the background of a View, set with
-{@link android.view.View#setBackgroundDrawable(android.graphics.drawable.Drawable) setBackgroundDrawable()}.
-Of course, you can also draw your shape as its own custom {@link android.view.View},
-to be added to your layout however you please.
-Because the ShapeDrawable has its own draw() method, you can create a subclass of View that
-draws the ShapeDrawable during the View.onDraw() method.
-Here's a basic extension of the View class that does just this, to draw a ShapeDrawable as a View:
-public class CustomDrawableView extends View {
- private ShapeDrawable mDrawable;
-
- public CustomDrawableView(Context context) {
- super(context);
-
- int x = 10;
- int y = 10;
- int width = 300;
- int height = 50;
-
- mDrawable = new ShapeDrawable(new OvalShape());
- mDrawable.getPaint().setColor(0xff74AC23);
- mDrawable.setBounds(x, y, x + width, y + height);
- }
-
- protected void onDraw(Canvas canvas) {
- mDrawable.draw(canvas);
- }
-}
-
-
-In the constructor, a ShapeDrawable is defines as an {@link android.graphics.drawable.shapes.OvalShape}. -It's then given a color and the bounds of the shape are set. If you do not set the bounds, then the -shape will not be drawn, whereas if you don't set the color, it will default to black.
-With the custom View defined, it can be drawn any way you like. With the sample above, we can -draw the shape progammatically in an Activity:
-
-CustomDrawableView mCustomDrawableView;
-
-protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mCustomDrawableView = new CustomDrawableView(this);
-
- setContentView(mCustomDrawableView);
-}
-
-
-If you'd like to draw this custom drawable from the XML layout instead of from the Activity, -then the CustomDrawable class must override the {@link android.view.View#View(android.content.Context, android.util.AttributeSet) View(Context, AttributeSet)} constructor, which is called when -instantiating a View via inflation from XML. Then add a CustomDrawable element to the XML, -like so:
--<com.example.shapedrawable.CustomDrawableView - android:layout_width="fill_parent" - android:layout_height="wrap_content" - /> -- -
The ShapeDrawable class (like many other Drawable types in the {@link android.graphics.drawable} package) -allows you to define various properties of the drawable with public methods. -Some properties you might want to adjust include -alpha transparency, color filter, dither, opacity and color.
- - - -A {@link android.graphics.drawable.NinePatchDrawable} graphic is a stretchable bitmap image, which Android
-will automatically resize to accomodate the contents of the View in which you have placed it as the background.
-An example use of a NinePatch is the backgrounds used by standard Android buttons —
-buttons must stretch to accommodate strings of various lengths. A NinePatch drawable is a standard PNG
-image that includes an extra 1-pixel-wide border. It must be saved with the extension .9.png,
-and saved into the res/drawable/ directory of your project.
-
- The border is used to define the stretchable and static areas of - the image. You indicate a stretchable section by drawing one (or more) 1-pixel-wide - black line(s) in the left and top part of the border. (You can have as - many stretchable sections as you want.) The relative size of the stretchable - sections stays the same, so the largest sections always remain the largest. -
-- You can also define an optional drawable section of the image (effectively, - the padding lines) by drawing a line on the right and bottom lines. - If a View object sets the NinePatch as its background and then specifies the - View's text, it will stretch itself so that all the text fits inside only - the area designated by the right and bottom lines (if included). If the - padding lines are not included, Android uses the left and top lines to - define this drawable area. -
-To clarify the difference between the different lines, the left and top lines define -which pixels of the image are allowed to be replicated in order to strech the image. -The bottom and right lines define the relative area within the image that the contents -of the View are allowed to lie within.
-- Here is a sample NinePatch file used to define a button: -
-
-
-This NinePatch defines one stretchable area with the left and top lines -and the drawable area with the bottom and right lines. In the top image, the dotted grey -lines identify the regions of the image that will be replicated in order to strech the image. The pink -rectangle in the bottom image identifies the region in which the contents of the View are allowed. -If the contents don't fit in this region, then the image will be stretched so that they do. -
- -The Draw 9-patch tool offers - an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. It -even raises warnings if the region you've defined for the stretchable area is at risk of -producing drawing artifacts as a result of the pixel replication. -
- -Here's some sample layout XML that demonstrates how to add a NinePatch image to a
-couple of buttons. (The NinePatch image is saved as res/drawable/my_button_background.9.png
-
-<Button id="@+id/tiny" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_alignParentTop="true" - android:layout_centerInParent="true" - android:text="Tiny" - android:textSize="8sp" - android:background="@drawable/my_button_background"/> - -<Button id="@+id/big" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_alignParentBottom="true" - android:layout_centerInParent="true" - android:text="Biiiiiiig text!" - android:textSize="30sp" - android:background="@drawable/my_button_background"/> --
Note that the width and height are set to "wrap_content" to make the button fit neatly around the text. -
- -Below are the two buttons rendered from the XML and NinePatch image shown above. -Notice how the width and height of the button varies with the text, and the background image -stretches to accommodate it. -
- -
-
-
-A tween animation can perform a series of simple transformations (position, size, rotation, and transparency) on -the contents of a View object. So, if you have a TextView object, you can move, rotate, grow, or shrink the text. -If it has a background image, the background image will be transformed along with the text. -The {@link android.view.animation animation package} provides all the classes used in a tween animation.
- -A sequence of animation instructions defines the twen animation, defined by either XML or Android code. -Like defining a layout, an XML file is recommended because it's more readable, reusable, and swappable -than hard-coding the animation. In the example below, we use XML. (To learn more about defining an animation -in your application code, instead of XML, refer to the -{@link android.view.animation.AnimationSet} class and other {@link android.view.animation.Animation} subclasses.)
- -The animation instructions define the transformations that you want to occur, when they will occur, -and how long they should take to apply. Transformations can be sequential or simultaneous — -for example, you can have the contents of a TextView move from left to right, and then -rotate 180 degrees, or you can have the text move and rotate simultaneously. Each transformation -takes a set of parameters specific for that transformation (starting size and ending size -for size change, starting angle and ending angle for rotation, and so on), and -also a set of common parameters (for instance, start time and duration). To make -several transformations happen simultaneously, give them the same start time; -to make them sequential, calculate the start time plus the duration of the preceding transformation. -
- -The animation XML file belongs in the res/anim/ directory of your Android project.
-The file must have a single root element: this will be either a single <alpha>,
-<scale>, <translate>, <rotate>, interpolator element,
-or <set> element that holds groups of these elements (which may include another
-<set>). By default, all animation instructions are applied simultaneously.
-To make them occur sequentially, you must specify the startOffset attribute, as shown in the example below.
-
The following XML from one of the ApiDemos is used to stretch, -then simultaneously spin and rotate a View object. -
--<set android:shareInterpolator="false"> - <scale - android:interpolator="@android:anim/accelerate_decelerate_interpolator" - android:fromXScale="1.0" - android:toXScale="1.4" - android:fromYScale="1.0" - android:toYScale="0.6" - android:pivotX="50%" - android:pivotY="50%" - android:fillAfter="false" - android:duration="700" /> - <set android:interpolator="@android:anim/decelerate_interpolator"> - <scale - android:fromXScale="1.4" - android:toXScale="0.0" - android:fromYScale="0.6" - android:toYScale="0.0" - android:pivotX="50%" - android:pivotY="50%" - android:startOffset="700" - android:duration="400" - android:fillBefore="false" /> - <rotate - android:fromDegrees="0" - android:toDegrees="-45" - android:toYScale="0.0" - android:pivotX="50%" - android:pivotY="50%" - android:startOffset="700" - android:duration="400" /> - </set> -</set> --
Screen coordinates (not used in this example) are (0,0) at the upper left hand corner, -and increase as you go down and to the right.
- -Some values, such as pivotX, can be specified relative to the object itself or relative to the parent. -Be sure to use the proper format for what you want ("50" for 50% relative to the parent, or "50%" for 50% -relative to itself).
- -You can determine how a transformation is applied over time by assigning an -{@link android.view.animation.Interpolator}. Android includes -several Interpolator subclasses that specify various speed curves: for instance, -{@link android.view.animation.AccelerateInterpolator} tells -a transformation to start slow and speed up. Each one has an attribute value that can be applied in the XML.
- -With this XML saved as hyperspace_jump.xml in the res/anim/ directory of the
-project, the following Java code will reference it and apply it to an {@link android.widget.ImageView} object
-from the layout.
-
-ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage); -Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump); -spaceshipImage.startAnimation(hyperspaceJumpAnimation); -- -
As an alternative to startAnimation(), you can define a starting time for the animation with
-{@link android.view.animation.Animation#setStartTime(long) Animation.setStartTime()},
-then assign the animation to the View with
-{@link android.view.View#setAnimation(android.view.animation.Animation) View.setAnimation()}.
-
For more information on the XML syntax, available tags and attributes, see the discussion on animation -in the Available Resources.
- -Note: Regardless of how your animation may move or resize, the bounds of the -View that holds your animation will not automatically adjust to accomodate it. Even so, the animation will still -be drawn beyond the bounds of its View and will not be clipped. However, clipping will occur -if the animation exceeds the bounds of the parent View.
- - -This is a traditional animation in the sense that it is created with a sequence of different -images, played in order, like a roll of film. The {@link android.graphics.drawable.AnimationDrawable} -class is the basis for frame animations.
- -While you can define the frames of an animation in your code, using the
-{@link android.graphics.drawable.AnimationDrawable} class API, it's more simply accomplished with a single XML
-file that lists the frames that compose the animation. Like the tween animation above, the XML file for this kind
-of animation belongs in the res/anim/ directory of your Android project. In this case,
-the instructions are the order and duration for each frame of the animation.
The XML file consists of an <animation-list> element as the root node and a series
-of child <item> nodes that each define a frame: a drawable resource for the frame and the frame duration.
-Here's an example XML file for a frame-by-frame animation:
-<animation-list xmlns:android="http://schemas.android.com/apk/res/android" - android:oneshot="true"> - <item android:drawable="@drawable/rocket_thrust1" android:duration="200" /> - <item android:drawable="@drawable/rocket_thrust2" android:duration="200" /> - <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /> -</animation-list> -- -
This animation runs for just three frames. By setting the android:oneshot attribute of the
-list to true, it will cycle just once then stop and hold on the last frame. If it is set false then
-the animation will loop. With this XML saved as rocket_thrust.xml
res/anim/ directory
-of the project, it can be added as the background image to a View and then called to play. Here's an example Activity,
-in which the animation is added to an {@link android.widget.ImageView} and then animated when the screen is touched:
-
-AnimationDrawable rocketAnimation;
-
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
- rocketImage.setBackgroundResource(R.anim.rocket_thrust);
- rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
-}
-
-public boolean onTouchEvent(MotionEvent event) {
- if (event.getAction() == MotionEvent.ACTION_DOWN) {
- rocketAnimation.start();
- return true;
- }
- return super.onTouchEvent(event);
-}
-
-It's important to note that the start() method called on the AnimationDrawable cannot be
-called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached
-to the window. If you want to play the animation immediately, without
-requiring interaction, then you might want to call it from the
-{@link android.app.Activity#onWindowFocusChanged(boolean) onWindowFocusChanged()} method in
-your Activity, which will get called when Android brings your window into focus.
Android graphics are powered by a custom 2D graphics library and OpenGL ES 1.0 -for high performance 3D graphics. The most common 2D graphics APIs can be found in the -{@link android.graphics.drawable drawable package}. OpenGL APIs are available -from the Khronos {@link javax.microedition.khronos.opengles OpenGL ES package}, -plus some Android {@link android.opengl OpenGL utilities}.
- -When starting a project, it's important to consider exactly what your graphical demands will be. -Varying graphical tasks are best accomplished with varying techniques. For example, graphics and animations -for a rather static application should be implemented much differently than graphics and animations -for an interactive game or 3D rendering.
- -Here, we'll discuss a few of the options you have for drawing graphics on Android, -and which tasks they're best suited for.
- -If you're specifically looking for information on drawing 3D graphics, this page won't -help a lot. However, the information below, on Drawing with a Canvas -(and the section on SurfaceView), -will give you a quick idea of how you should draw to the View hierarchy. For more information -on Android's 3D graphic utilities (provided by the OpenGL ES API), -read 3D with OpenGL and refer to other OpenGL documentation.
- - -When drawing 2D graphics, you'll typically do so in one of two ways:
-draw() method (passing it your Canvas), or one of the Canvas draw...() methods (like
- {@link android.graphics.Canvas#drawPicture(Picture,Rect) drawPicture()}). In doing so, you are also in
- control of any animation.Option "a," drawing to a View, is your best choice when you want to draw simple graphics that do not -need to change dynamically and are not part of a performance-intensive game. For example, you should -draw your graphics into a View when you want to display a static graphic or predefined animation, within -an otherwise static application. Read Simple Graphics Inside a View. - -
Option "b," drawing to a Canvas, is better when you're application needs to regularly re-draw itself. -Basically, any video game should be drawing to the Canvas on its own. However, there's more than -one way to do this:
-{@link android.view.View#invalidate()} and then handle the
- {@link android.view.View#onDraw(Canvas) onDraw()} callback..invalidate())....Begin by reading Draw with a Canvas.
- -If you'll be drawing some simple graphics (images, shapes, colors, pre-defined animations, etc.), -then you should probably just draw to the background of a View or -to the content of an {@link android.widget.ImageView} in your layout. -In this case, you can skip the rest of this document and learn how to -draw graphics and animations in the 2D Graphics document. -
- - -When you're writing an application in which you would like to perform specialized drawing -and/or control the animation of graphics, -you should do so by drawing through a {@link android.graphics.Canvas}. A Canvas works for you as -a pretense, or interface, to the actual surface upon which your graphics will be drawn — it -holds all of your "draw" calls. Via the Canvas, your drawing is actually performed upon an -underlying {@link android.graphics.Bitmap}, which is placed into the window.
- -In the event that you're drawing within the {@link android.view.View#onDraw(Canvas) onDraw()}
-callback method, the Canvas is provided for you and you need only place your drawing calls upon it.
-You can also acquire a Canvas from {@link android.view.SurfaceHolder#lockCanvas() SurfaceHolder.lockCanvas()},
-when dealing with a SurfaceView object. (Both of these scenarios are discussed in the following sections.)
-However, if you need to create a new Canvas, then you must define the {@link android.graphics.Bitmap}
-upon which drawing will actually be performed. The Bitmap is always required for a Canvas. You can set up
-a new Canvas like this:
-Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); -Canvas c = new Canvas(b); -- -
Now your Canvas will draw onto the defined Bitmap. After drawing upon it with the Canvas, you can then carry your
-Bitmap to another Canvas with one of the {@link android.graphics.Canvas#drawBitmap(Bitmap,Matrix,Paint)
-Canvas.drawBitmap(Bitmap,...)} methods. It's recommended that you ultimately draw your final
-graphics through a Canvas offered to you
-by {@link android.view.View#onDraw(Canvas) View.onDraw()} or
-{@link android.view.SurfaceHolder#lockCanvas() SurfaceHolder.lockCanvas()} (see the following sections).
The {@link android.graphics.Canvas} class has its own set of drawing methods that you can use,
-like drawBitmap(...), drawRect(...), drawText(...), and many more.
-Other classes that you might use also have draw() methods. For example, you'll probably
-have some {@link android.graphics.drawable.Drawable} objects that you want to put on the Canvas. Drawable
-has its own {@link android.graphics.drawable.Drawable#draw(Canvas) draw()} method
-that takes your Canvas as an arguement.
If you're application does not require a significant amount of processing or
-frame-rate speed (perhaps for a chess game, a snake game,
-or another slowly-animated application), then you should consider creating a custom View component
-and drawing with a Canvas in {@link android.view.View#onDraw(Canvas) View.onDraw()}.
-The most convenient aspect of doing so is that the Android framework will
-provide you with a pre-defined Canvas to which you will place your drawing calls.
To start, extend the {@link android.view.View} class (or descendent thereof) and define
-the {@link android.view.View#onDraw(Canvas) onDraw()} callback method. This method will be called by the Android
-framework to request that your View draw itself. This is where you will perform all your calls
-to draw through the {@link android.graphics.Canvas}, which is passed to you through the onDraw() callback.
The Android framework will only call onDraw() as necessary. Each time that
-your application is prepared to be drawn, you must request your View be invalidated by calling
-{@link android.view.View#invalidate()}. This indicates that you'd like your View to be drawn and
-Android will then call your onDraw() method (though is not guaranteed that the callback will
-be instantaneous).
Inside your View component's onDraw(), use the Canvas given to you for all your drawing,
-using various Canvas.draw...() methods, or other class draw() methods that
-take your Canvas as an argument. Once your onDraw() is complete, the Android framework will
-use your Canvas to draw a Bitmap handled by the system.
Note: In order to request an invalidate from a thread other than your main
-Activity's thread, you must call {@link android.view.View#postInvalidate()}.
Also read Building Custom Components -for a guide to extending a View class, and 2D Graphics: Drawables for -information on using Drawable objects like images from your resources and other primitive shapes.
- -For a sample application, see the Snake game, in the SDK samples folder:
-<your-sdk-directory>/samples/Snake/.
The {@link android.view.SurfaceView} is a special subclass of View that offers a dedicated -drawing surface within the View hierarchy. The aim is to offer this drawing surface to -an application's secondary thread, so that the application isn't required -to wait until the system's View hierarchy is ready to draw. Instead, a secondary thread -that has reference to a SurfaceView can draw to its own Canvas at its own pace.
- -To begin, you need to create a new class that extends {@link android.view.SurfaceView}. The class should also -implement {@link android.view.SurfaceHolder.Callback}. This subclass is an interface that will notify you -with information about the underlying {@link android.view.Surface}, such as when it is created, changed, or destroyed. -These events are important so that you know when you can start drawing, whether you need -to make adjustments based on new surface properties, and when to stop drawing and potentially -kill some tasks. Inside your SurfaceView class is also a good place to define your secondary Thread class, which will -perform all the drawing procedures to your Canvas.
- -Instead of handling the Surface object directly, you should handle it via
-a {@link android.view.SurfaceHolder}. So, when your SurfaceView is initialized, get the SurfaceHolder by calling
-{@link android.view.SurfaceView#getHolder()}. You should then notify the SurfaceHolder that you'd
-like to receive SurfaceHolder callbacks (from {@link android.view.SurfaceHolder.Callback}) by calling
-{@link android.view.SurfaceHolder#addCallback(SurfaceHolder.Callback) addCallback()}
-(pass it this). Then override each of the
-{@link android.view.SurfaceHolder.Callback} methods inside your SurfaceView class.
In order to draw to the Surface Canvas from within your second thread, you must pass the thread your SurfaceHandler
-and retrieve the Canvas with {@link android.view.SurfaceHolder#lockCanvas() lockCanvas()}.
-You can now take the Canvas given to you by the SurfaceHolder and do your necessary drawing upon it.
-Once you're done drawing with the Canvas, call
-{@link android.view.SurfaceHolder#unlockCanvasAndPost(Canvas) unlockCanvasAndPost()}, passing it
-your Canvas object. The Surface will now draw the Canvas as you left it. Perform this sequence of locking and
-unlocking the canvas each time you want to redraw.
Note: On each pass you retrieve the Canvas from the SurfaceHolder,
-the previous state of the Canvas will be retained. In order to properly animate your graphics, you must re-paint the
-entire surface. For example, you can clear the previous state of the Canvas by filling in a color
-with {@link android.graphics.Canvas#drawColor(int) drawColor()} or setting a background image
-with {@link android.graphics.Canvas#drawBitmap(Bitmap,Rect,RectF,Paint) drawBitmap()}. Otherwise,
-you will see traces of the drawings you previously performed.
For a sample application, see the Lunar Landar game, in the SDK samples folder:
-<your-sdk-directory>/samples/LunarLander/. Or,
-browse the source in the Sample Code section.
Android includes support for high performance 3D graphics -via the OpenGL API — specifically, the OpenGL ES API.
- -OpenGL ES is a flavor of the OpenGL specification intended for embedded -devices. Versions of OpenGL ES are loosely peered to versions of the primary -OpenGL standard. Android currently supports OpenGL ES 1.0, which corresponds -to OpenGL 1.3. So, if the application you have in mind is possible with OpenGL -1.3 on a desktop system, it should be possible on Android.
- -The specific API provided by Android is similar to the J2ME JSR239 OpenGL -ES API. However, it may not be identical, so watch out for deviations.
- -Here's how to use the API at an extremely high level:
- -For an example of this usage model (based on the classic GL ColorCube), -see -com.android.samples.graphics.GLSurfaceView.java -in the ApiDemos sample code project. A slightly more sophisticated version showing how to use -it with threads can be found in -com.android.samples.graphics.GLSurfaceViewActivity.java. -
- -Writing a summary of how to actually write 3D applications using OpenGL is -beyond the scope of this text and is left as an exercise for the reader.
- -Information about OpenGL ES can be -found at http://www.khronos.org/opengles/.
- -Information specifically -about OpenGL ES 1.0 (including a detailed specification) can be found -at http://www.khronos.org/opengles/1_X/.
- -The documentation for the Android {@link javax.microedition.khronos.opengles -OpenGL ES implementations} are also available.
- -Finally, note that though Android does include some basic support for -OpenGL ES 1.1, the support is not complete, and should not be relied -upon at this time.
diff --git a/docs/html/guide/topics/index.html b/docs/html/guide/topics/index.html deleted file mode 100644 index 4881acf..0000000 --- a/docs/html/guide/topics/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/topics/intents/index.html b/docs/html/guide/topics/intents/index.html deleted file mode 100644 index b831246..0000000 --- a/docs/html/guide/topics/intents/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - --Three of the core components of an application — activities, services, and -broadcast receivers — are activated through messages, called intents. -Intent messaging is a facility for late run-time binding between components in the same -or different applications. The intent itself, an {@link android.content.Intent} -object, is a passive data structure holding an abstract description of an operation -to be performed — or, in the case of broadcasts, a description of something -that has happened and is being announced. There are separate mechanisms for -delivering intents to each type of component: -
- -{@link android.content.Context#startActivity
-Context.startActivity()} or {@link android.app.Activity#startActivityForResult
-Activity.startActivityForResult()} to launch an activity or get an existing
-activity to do something new.An Intent object is passed to {@link android.content.Context#startService
-Context.startService()} to initiate a service or deliver new instructions to an
-ongoing service. Similarly, an intent can be passed to {@link
-android.content.Context#bindService Context.bindService()} to establish a
-connection between the calling component and a target service. It can optionally
-initiate the service if it's not already running.
Intent objects passed to any of the broadcast methods (such as {@link
-android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()},
-{@link android.content.Context#sendOrderedBroadcast(Intent, String)
-Context.sendOrderedBroadcast()}, or {@link
-android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()})
-are delivered to all interested broadcast receivers. Many kinds of broadcasts
-originate in system code.
-In each case, the Android system finds the appropriate activity, service, or set -of broadcast receivers to respond to the intent, instantiating them if necessary. -There is no overlap within these messaging systems: Broadcast intents are delivered -only to broadcast receivers, never to activities or services. An intent passed to -{@code startActivity()} is delivered only to an activity, never to a service or -broadcast receiver, and so on. -
- --This document begins with a description of Intent objects. It then describes the -rules Android uses to map intents to components — how it resolves which -component should receive an intent message. For intents that don't explicitly -name a target component, this process involves testing the Intent object against -intent filters associated with potential targets. -
- - --An {@link android.content.Intent} object is a bundle of information. It -contains information of interest to the component that receives the intent -(such as the action to be taken and the data to act on) plus information -of interest to the Android system (such as the category of component that -should handle the intent and instructions on how to launch a target activity). -Principally, it can contain the following: -
- --The component name is optional. If it is set, the Intent object is -delivered to an instance of the designated class. If it is not set, -Android uses other information in the Intent object to locate a suitable -target — see Intent Resolution, later in this -document. -
- -
-The component name is set by {@link android.content.Intent#setComponent
-setComponent()}, {@link android.content.Intent#setClass
-setClass()}, or {@link android.content.Intent#setClassName(String, String)
-setClassName()} and read by {@link android.content.Intent#getComponent
-getComponent()}.
-
| Constant | -Target component | -Action | -
|---|---|---|
| {@code ACTION_CALL} - | activity - | Initiate a phone call. - |
| {@code ACTION_EDIT} - | activity - | Display data for the user to edit. - |
| {@code ACTION_MAIN} - | activity - | Start up as the initial activity of a task, with no data input and no returned output. - |
| {@code ACTION_SYNC} - | activity - | Synchronize data on a server with data on the mobile device. - |
| {@code ACTION_BATTERY_LOW} - | broadcast receiver - | A warning that the battery is low. - |
| {@code ACTION_HEADSET_PLUG} - | broadcast receiver - | A headset has been plugged into the device, or unplugged from it. - |
| {@code ACTION_SCREEN_ON} - | broadcast receiver - | The screen has been turned on. - |
| {@code ACTION_TIMEZONE_CHANGED} - | broadcast receiver - | The setting for the time zone has changed. - |
-See the {@link android.content.Intent} class description for a list of
-pre-defined constants for generic actions. Other actions are defined
-elsewhere in the Android API.
-You can also define your own action strings for activating the components
-in your application. Those you invent should include the application
-package as a prefix — for example:
-"com.example.project.SHOW_COLOR".
-
-The action largely determines how the rest of the intent is structured -— particularly the data and -extras fields — -much as a method name determines a set of arguments and a return value. -For this reason, it's a good idea to use action names that are -as specific as possible, and to couple them tightly to the other fields of -the intent. In other words, instead of defining an action in isolation, -define an entire protocol for the Intent objects your components can handle. -
- -
-The action in an Intent object is set by the
-{@link android.content.Intent#setAction setAction()}
-method and read by
-{@link android.content.Intent#getAction getAction()}.
-
-When matching an intent to a component that is capable of handling the data, -it's often important to know the type of data (its MIME type) in addition to its URI. -For example, a component able to display image data should not be called -upon to play an audio file. -
- -
-In many cases, the data type can be inferred from the URI — particularly
-{@code content:} URIs, which indicate that the data is located on the device and
-controlled by a content provider (see the
-separate
-discussion on content providers). But the type can also be explicitly set
-in the Intent object.
-The {@link android.content.Intent#setData setData()} method specifies
-data only as a URI, {@link android.content.Intent#setType setType()}
-specifies it only as a MIME type, and {@link
-android.content.Intent#setDataAndType setDataAndType()} specifies it as both
-a URI and a MIME type. The URI is read by {@link
-android.content.Intent#getData getData()} and the type by {@link
-android.content.Intent#getType getType()}.
-
| Constant | -Meaning | -
|---|---|
| {@code CATEGORY_BROWSABLE} - | The target activity can be safely invoked by the browser to display data - referenced by a link — for example, an image or an e-mail message. - |
| {@code CATEGORY_GADGET} - | The activity can be embedded inside of another activity that hosts gadgets. - |
| {@code CATEGORY_HOME} - | The activity displays the home screen, the first screen the user sees when - the device is turned on or when the HOME key is pressed. - |
| {@code CATEGORY_LAUNCHER} - | The activity can be the initial activity of a task and is listed in - the top-level application launcher. - |
| {@code CATEGORY_PREFERENCE} - | The target activity is a preference panel. - |
-See the {@link android.content.Intent} class description for the full list of -categories. -
- -
-The {@link android.content.Intent#addCategory addCategory()} method
-places a category in an Intent object, {@link android.content.Intent#removeCategory
-removeCategory()} deletes a category previously added, and {@link android.content.Intent#getCategories getCategories()} gets the set of all
-categories currently in the object.
-
-The Intent object has a series of {@code put...()} methods for inserting various
-types of extra data and a similar set of {@code get...()} methods for reading
-the data. These methods parallel those for {@link android.os.Bundle} objects.
-In fact, the extras can be installed and read as a Bundle using the {@link
-android.content.Intent#putExtras putExtras()} and {@link
-android.content.Intent#getExtras getExtras()} methods.
-
-The Android system and the applications that come with the platform employ -Intent objects both to send out system-originated broadcasts and to activate -system-defined components. To see how to structure an intent to activate a -system component, consult the -list of intents -in the reference. -
- - --Intents can be divided into two groups: -
- -Implicit intents do not name a target (the field for -the component name is blank). Implicit intents are often used to -activate components in other applications.
-Android delivers an explicit intent to an instance of the designated -target class. Nothing in the Intent object other than the component -name matters for determining which component should get the intent. -
- --A different strategy is needed for implicit intents. In the absence of a -designated target, the Android system must find the best component (or -components) to handle the intent — a single activity or service to -perform the requested action or the set of broadcast receivers to respond -to the broadcast announcement. It does so by comparing the contents of -the Intent object to intent filters, structures associated with -components that can potentially receive intents. Filters advertise the -capabilities of a component and delimit the intents it can handle. They -open the component to the possibility of receiving implicit intents of -the advertised type. If a component does not have any intent filters, -it can receive only explicit intents. A component with filters can -receive both explicit and implicit intents. -
- --Only three aspects of an Intent object are consulted when the object -is tested against an intent filter: -
- -action
-
data (both URI and data type)
-
category
-The extras and flags play no part in resolving which component receives -an intent. -
- - --To inform the system which implicit intents they can handle, activities, -services, and broadcast receivers can have one or more intent filters. -Each filter describes a capability of the component, a set of intents that -the component is willing to receive. It, in effect, filters in -intents of a desired type, while filtering out unwanted -intents — but only unwanted implicit intents (those that don't name -a target class). An explicit intent is always delivered to its target, -no matter what it contains; the filter is not consulted. But an implicit -intent is delivered to a component only if it can pass through one of the -component's filters. -
- --A component has separate filters for each job it can do, each face it can -present to the user. For example, the principal activity of the sample -NotePad application has three filters — one for starting up with a -blank slate, another for starting with an assigned directory of notes -that the user can view, edit, or select from, and a third for finding a -particular note without an initial specification of its directory. -
- -
-An intent filter is an instance of the {@link android.content.IntentFilter} class.
-However, since the Android system must know about the capabilities of a component
-before it can launch that component, intent filters are generally not set up in
-Java code, but in the application's manifest file (AndroidManifest.xml) as
-{@code <intent-filter>} elements. (The one exception would be filters for
-broadcast receivers that are registered dynamically by calling {@link android.content.Context#registerReceiver(BroadcastReceiver, IntentFilter, String,
-Handler) Context.registerReceiver()}; they are directly created as
-IntentFilter objects.)
-
An intent filter cannot be relied on for security. While it opens a -component to receiving only certain kinds of implicit intents, it does -nothing to prevent explicit intents from targeting the component. Even -though a filter restricts the intents a component will be asked to handle -to certain actions and data sources, someone could always put -together an explicit intent with a different action and data source, and -name the component as the target. -
--A filter has fields that parallel the action, data, and category fields of an -Intent object. An implicit intent is tested against the filter in all three areas. -To be delivered to the component that owns the filter, it must pass all three tests. -If it fails even one of them, the Android system won't deliver it to the -component — at least not on the basis of that filter. However, since a -component can have multiple intent filters, an intent that does not pass -through one of a component's filters might make it through on another. -
- --Each of the three tests is described in detail below: -
- -<intent-filter . . . > - <action android:name="com.example.project.SHOW_CURRENT" /> - <action android:name="com.example.project.SHOW_RECENT" /> - <action android:name="com.example.project.SHOW_PENDING" /> - . . . -</intent-filter>- -
-As the example shows, while an Intent object names just a single action, -a filter may list more than one. The list cannot be empty; a filter must -contain at least one {@code <action>} element, or it -will block all intents. -
- --To pass this test, the action specified in the Intent object must match -one of the actions listed in the filter. If the object or the filter -does not specify an action, the results are as follows: -
- -On the other hand, an Intent object that doesn't specify an -action automatically passes the test — as long as the filter -contains at least one action.
<intent-filter . . . > - <category android:name="android.intent.category.DEFAULT" /> - <category android:name="android.intent.category.BROWSABLE" /> - . . . -</intent-filter>- -
-Note that the constants described earlier for actions and categories are not -used in the manifest file. The full string values are used instead. For -instance, the "{@code android.intent.category.BROWSABLE}" string in the example -above corresponds to the {@code CATEGORY_BROWSABLE} constant mentioned earlier -in this document. Similarly, the string "{@code android.intent.action.EDIT}" -corresponds to the {@code ACTION_EDIT} constant. -
- --For an intent to pass the category test, every category in the Intent object -must match a category in the filter. The filter can list additional categories, -but it cannot omit any that are in the intent. -
- --In principle, therefore, an Intent object with no categories should always pass -this test, regardless of what's in the filter. That's mostly true. However, -with one exception, Android treats all implicit intents passed to {@link -android.content.Context#startActivity startActivity()} as if they contained -at least one category: "{@code android.intent.category.DEFAULT}" (the -{@code CATEGORY_DEFAULT} constant). -Therefore, activities that are willing to receive implicit intents must -include "{@code android.intent.category.DEFAULT}" in their intent filters. -(Filters with "{@code android.intent.action.MAIN}" and -"{@code android.intent.category.LAUNCHER}" settings are the exception. -They mark activities that begin new tasks and that are represented on the -launcher screen. They can include "{@code android.intent.category.DEFAULT}" -in the list of categories, but don't need to.) See Using -intent matching, later, for more on these filters.) -
-<intent-filter . . . > - <data android:type="video/mpeg" android:scheme="http" . . . /> - <data android:type="audio/mpeg" android:scheme="http" . . . /> - . . . -</intent-filter>- -
-Each {@code <data>} element can specify a URI and a data type (MIME media type). -There are separate attributes — {@code scheme}, {@code host}, {@code port}, -and {@code path} — for each part of the URI: -
- -{@code scheme://host:port/path}
- --For example, in the following URI, -
- -{@code content://com.example.project:200/folder/subfolder/etc}
- -the scheme is "{@code content}", the host is "{@code com.example.project}", -the port is "{@code 200}", and the path is "{@code folder/subfolder/etc}". -The host and port together constitute the URI authority; if a host is -not specified, the port is ignored. -
- --Each of these attributes is optional, but they are not independent of each other: -For an authority to be meaningful, a scheme must also be specified. -For a path to be meaningful, both a scheme and an authority must be specified. -
- --When the URI in an Intent object is compared to a URI specification in a filter, -it's compared only to the parts of the URI actually mentioned in the filter. -For example, if a filter specifies only a scheme, all URIs with that scheme match -the filter. If a filter specifies a scheme and an authority but no path, all URIs -with the same scheme and authority match, regardless of their paths. If a filter -specifies a scheme, an authority, and a path, only URIs with the same scheme, -authority, and path match. However, a path specification in the filter can -contain wildcards to require only a partial match of the path. -
- --The {@code type} attribute of a {@code <data>} element specifies the MIME type -of the data. It's more common in filters than a URI. Both the Intent object and -the filter can use a "*" wildcard for the subtype field — for example, -"{@code text/*}" or "{@code audio/*}" — indicating any subtype matches. -
- --The data test compares both the URI and the data type in the Intent object to a URI -and data type specified in the filter. The rules are as follows: -
- -An Intent object that contains a URI but no data type (and a type cannot -be inferred from the URI) passes the test only if its URI matches a URI in the -filter and the filter likewise does not specify a type. This will be the case -only for URIs like {@code mailto:} and {@code tel:} that do not refer to actual data.
An Intent object that contains a data type but not a URI passes the test -only if the filter lists the same data type and similarly does not specify a URI.
An Intent object that contains both a URI and a data type (or a data type -can be inferred from the URI) passes the data type part of the test only if its -type matches a type listed in the filter. It passes the URI part of the test -either if its URI matches a URI in the filter or if it has a {@code content:} -or {@code file:} URI and the filter does not specify a URI. In other words, -a component is presumed to support {@code content:} and {@code file:} data if -its filter lists only a data type.
-If an intent can pass through the filters of more than one activity or service, -the user may be asked which component to activate. An exception is raised if -no target can be found. -
- - --The last rule shown above for the data test, rule (d), reflects the expectation -that components are able to get local data from a file or content provider. -Therefore, their filters can list just a data type and do not need to explicitly -name the {@code content:} and {@code file:} schemes. -This is a typical case. A {@code <data>} element like the following, -for example, tells Android that the component can get image data from a content -provider and display it: -
- -<data android:type="image/*" />- -
-Since most available data is dispensed by content providers, filters that -specify a data type but not a URI are perhaps the most common. -
- --Another common configuration is filters with a scheme and a data type. For -example, a {@code <data>} element like the following tells Android that -the component can get video data from the network and display it: -
- -<data android:scheme="http" android:type="video/*" />- -
-Consider, for example, what the browser application does when -the user follows a link on a web page. It first tries to display the data -(as it could if the link was to an HTML page). If it can't display the data, -it puts together an implicit intent with the scheme and data type and tries -to start an activity that can do the job. If there are no takers, it asks the -download manager to download the data. That puts it under the control -of a content provider, so a potentially larger pool of activities -(those with filters that just name a data type) can respond. -
- --Most applications also have a way to start fresh, without a reference -to any particular data. Activities that can initiate applications -have filters with "{@code android.intent.action.MAIN}" specified as -the action. If they are to be represented in the application launcher, -they also specify the "{@code android.intent.category.LAUNCHER}" -category: -
- -<intent-filter . . . > - <action android:name="code android.intent.action.MAIN" /> - <category android:name="code android.intent.category.LAUNCHER" /> -</intent-filter>- - -
-Intents are matched against intent filters not only to discover a target -component to activate, but also to discover something about the set of -components on the device. For example, the Android system populates the -application launcher, the top-level screen that shows the applications -that are available for the user to launch, by finding all the activities - with intent filters that specify the "{@code android.intent.action.MAIN}" -action and "{@code android.intent.category.LAUNCHER}" category -(as illustrated in the previous section). It then displays the icons and -labels of those activities in the launcher. Similarly, it discovers the -home screen by looking for the activity with -"{@code android.intent.category.HOME}" in its filter. -
- --Your application can use intent matching is a similar way. -The {@link android.content.pm.PackageManager} has a set of {@code query...()} -methods that return all components that can accept a particular intent, and -a similar series of {@code resolve...()} methods that determine the best -component to respond to an intent. For example, -{@link android.content.pm.PackageManager#queryIntentActivities -queryIntentActivities()} returns a list of all activities that can perform -the intent passed as an argument, and {@link -android.content.pm.PackageManager#queryIntentServices -queryIntentServices()} returns a similar list of services. -Neither method activates the components; they just list the ones that -can respond. There's a similar method, -{@link android.content.pm.PackageManager#queryBroadcastReceivers -queryBroadcastReceivers()}, for broadcast receivers. -
- - - - - - - - - - - diff --git a/docs/html/guide/topics/location/geo/mapkey.jd b/docs/html/guide/topics/location/geo/mapkey.jd deleted file mode 100644 index 9aa824c..0000000 --- a/docs/html/guide/topics/location/geo/mapkey.jd +++ /dev/null @@ -1,210 +0,0 @@ -page.title=Obtaining a Maps API Key -@jd:body - -To register for a Maps API Key, read this document and then go to the Android Maps API Key Signup page.
- -com.google.android.maps.MapView is a very useful class that lets you easily integrate Google Maps into your application. It provides built-in map downloading, rendering, and caching of Maps tiles, as well as a variety of display options and controls. It provides a wrapper around the Google Maps API that lets your application request and manipulate Google Maps data through class methods, and it lets you work with Maps data as you would other types of Views.
- -Because MapView gives you access to Google Maps data, you need to register with the Google Maps service and agree to the applicable Terms of Service before your MapView will be able to obtain data from Google Maps. This will apply whether you are developing your application on the emulator or preparing your application for deployment to mobile devices.
- -Registering for a Maps API Key is simple, free, and has two parts:
- -During registration, you also need to agree to the Maps API Terms of Service, which describe how your application can use the Maps data. In general, the terms of service are permissive and place few restrictions on how you can use the data. For example, the terms allow you to build "friend finder" type applications.
- -The sections below describe how to obtain your Maps API Key and how to reference it from your MapView elements.
- -MapView objects are views that display Maps tiles downloaded from the Google Maps service. To ensure that applications use Maps data in an appropriate manner, the Google Maps service requires application developers to register with the service, agreeing to the Terms of Service and supplying an MD5 fingerprint of the certificate(s) that they will use to sign applications. For each registered certificate fingerprint, the service then provides the developer with a Maps API Key — an alphanumeric string that uniquely identifies the certificate and developer registered with the service.
- -The Google Maps service also requires that each MapView identify itself to the service using a Maps API Key. Before providing Maps tiles to a MapView, the service checks the Maps API Key supplied by the MapView to ensure that it:
-Unless both conditions are met, the service does not provide Maps tiles to the MapView.
- -Each MapView object in your application must reference a Maps API Key. Since the Key is associated with a certificate, all Mapview elements in an application should reference the same Key. Going a step further, all MapView elements in all applications that you sign with the same certificate should reference the same Key.
- -On the other hand, you can register for multiple Maps API Keys, each being associated with a specific certificate. You would want to do this if, for example, you were developing several independent applications that you will sign using different certificates. In this case, note that all MapView elements in a given application can reference the same Maps API Key, but must reference the Key that is associated with the certificate used to sign the application.
- -Because MapView elements must refer to a Maps API Key, you need to register your certificate and receive a Key before you can make use of MapView elements in your application. To make it easier for you to get started using MapView elements, you are welcome to register the debug certificate generated by the SDK tools and receive a temporary Maps API Key. The details of how to do that are given below.
- -When you are preparing to release your application, however, note that you must sign your application with a suitable cryptographic key, rather than the SDK debug key. That means that you will also need to register your application's release certificate with the Google Maps service. After you've done so, you will receive a new Maps API Key that is uniquely associated with your release certificate. To enable the MapView elements in your application to work after release, you must remember to change the Maps API Key for all MapViews in your application so that they refer to the Key associated with your release certificate (rather than your debug certificate).
- -To summarize, the important points to understand about MapViews and the Maps API Key are:
- -To register for a Maps API Key, you need to provide an MD5 fingerprint of the certificate that you will use to sign your application.
- -Before you visit the registration page, use Keytool to generate the fingerprint of the appropriate certificate. - -
First, determine which key you will use to sign your application at release and make sure of the path to the keystore that contains it.
- -Next, run Keytool with the -list option, against the target keystore and key alias. The table below lists the options you should use.
| Keytool Option | -Description | -
|---|---|
-list | Print an MD5 fingerprint of a certificate. | -
-keystore <keystore-name>.keystore | The name of the keystore containing the target key. | -
-storepass <password> | A password for the -keystore. As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
-alias <alias_name> | The alias for the key for which to generate the MD5 certificate fingerprint. | -
-keypass <password> | The password for the key. -As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history. |
-
Here's an example of a Keytool command that generates an MD5 certificate fingerprint for the key alias_name in the keystore my-release-key.keystore:
$ keytool -list -alias alias_name -keystore my-release-key.keystore- -
Keytool will prompt you to enter passwords for the keystore and key. As output of the command, Keytool prints the fingerprint to the shell. For example:
- -Certificate fingerprint (MD5): 94:1E:43:49:87:73:BB:E6:A6:88:D7:20:F1:8E:B5:98- -
Note that, if you happen to forget your Maps API Key, you can repeat the process described above and register the fingerprint again. The server will give you the same key for the specified certificate fingerprint.
- -Once you have the fingerprint, you can go to the Maps API registration site, described next.
- -While you are developing and debugging your application, you will likely be -sigining your application in debug mode — that is, the SDK build tools -will automatically sign your application using the debug certificate. To let -your MapView elements properly display Maps data during this period, you should -obtain a temporary Maps API Key registered to the debug certificate. To do so, -you first need to get the MD5 fingerprint of the debug certificate. When -you are ready to release your application, you must register your release -certificate with the Google Maps service and obtain a new Maps API Key. You must -then change the MapView elements in your application to reference the new API -key.
- -To generate an MD5 fingerprint of the debug certificate, first locate the debug keystore. The location at which the SDK tools create the default debug keystore varies by platform:
- -C:\Users\<user>\AppData\Local\Android\debug.keystoreC:\Documents and Settings\<user>\Local Settings\Application Data\Android\debug.keystore~/.android/debug.keystoreIf you are using Eclipse/ADT and are unsure where the debug keystore is located, you can select Windows > Prefs > Android > Build to check the full path, which you can then paste into a file explorer to locate the directory containing the keystore.
- -Once you have located the keystore, use this Keytool command to get the MD5 fingerprint of the debug certificate:
- -$ keytool -list -alias androiddebugkey \ --keystore <path_to_debug_keystore>.keystore \ --storepass android -keypass android- -
When you are ready to register for a Maps API Key, load this page in a browser:
- -http://code.google.com/android/maps-api-signup.html
- -To register for a Maps API Key, follow these steps:
- -The server will handle your request, associating the fingerprint with your developer identity and generating a unique Maps API Key, then returning a results page that gives you your Key string.
- -To use the Maps API Key string, copy and paste it into your code as described in the next section.
- -Once you've registered with the Google Maps service and have obtained a Maps API Key, you must add it to your application's MapView objects, so that the Maps server will allow them to download Maps tiles.
- -For <MapView> elements declared in XML layout files, add the Maps API Key as the value of a special attribute — android:apiKey. For example:
-
-
<com.google.android.maps.MapView - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:enabled="true" - android:clickable="true" - android:apiKey="example_Maps_ApiKey_String" - />- - -
For MapView objects instantiated directly from code, pass the Maps API Key string as a parameter in the constructor. For example:
- -mMapView = new MapView(this, "example_Maps_ApiKey_String");- -
For more information about MapView, see the MapView class Documentation.
- -If you've added the Maps API Key to the MapViews in your application, here are the final steps to enable the MapView elements to run properly:
- -<uses-library> element referencing the external com.google.android.maps library. The element must be a child of the <application> element in the application's manifest. For example:
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.example.package.name"> - ... - <application android:name="MyApplication" > - <uses-library android:name="com.google.android.maps" /> - ... - </application>
Note that, when you are ready to publish your application, you must get a Maps API Key that is based on the certificate that you will use to sign the application for release. You must then change the Maps API Key string referenced by all of your MapView elements, so that they reference the new Key.
The Android SDK includes two packages that provide Android's primary support -for building location-based services: -{@link android.location} and {@link-fixme com.google.android.maps}. -Please read on below for a brief introduction to each package.
- -This package contains several classes related to -location services in the Android platform. Most importantly, it introduces the -{@link android.location.LocationManager} -service, which provides an API to determine location and bearing if the -underlying device (if it supports the service). The LocationManager -should not be -instantiated directly; rather, a handle to it should be retrieved via -{@link android.content.Context#getSystemService(String) -getSystemService(Context.LOCATION_SERVICE)}.
- -Once your application has a handle to the LocationManager, your application -will be able to do three things:
- -However, during initial development, you may not have access to real -data from a real location provider (Network or GPS). So it may be necessary to -spoof some data for your application, with some mock location data.
- -Note: If you've used mock LocationProviders in -previous versions of the SDK (m3/m5), you can no longer provide canned LocationProviders -in the /system/etc/location directory. These directories will be wiped during boot-up. -Please follow the new procedures below.
- - -When testing your application on the Android emulator, there are a couple different -ways to send it some spoof location data: with the DDMS tool or the "geo" command.
- -With the DDMS tool, you can simulate location data a few different ways:
-For more information on using DDMS to spoof location data, see the -Using DDMS guide. - -
Launch your application in the Android emulator and open a terminal/console in
-your SDK's /tools directory. Now you can use:
geo fix to send a fixed geo-location.
- This command accepts a longitude and latitude in decimal degrees, and - an optional altitude in meters. For example:
-geo fix -121.45356 46.51119 4392-
geo nmea to send an NMEA 0183 sentence.
- This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit data). - For example:
-geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62-
This package introduces a number of classes related to -rendering, controlling, and overlaying customized information on your own -Google Mapified Activity. The most important of which is the -{@link-fixme com.google.android.maps.MapView} class, which automagically draws you a -basic Google Map when you add a MapView to your layout. Note that, if you -want to do so, then your Activity that handles the -MapView must extend {@link-fixme com.google.android.maps.MapActivity}.
- -Also note that you must obtain a MapView API Key from the Google Maps -service, before your MapView can load maps data. For more information, see -Obtaining a MapView API Key.
- -Once you've created a MapView, you'll probably want to use -{@link-fixme com.google.android.maps.MapView#getController()} to -retrieve a {@link-fixme com.google.android.maps.MapController}, for controlling and -animating the map, and {@link-fixme com.google.android.maps.ItemizedOverlay} to -draw {@link-fixme com.google.android.maps.Overlay}s and other information on the Map.
- -This is not a standard package in the Android library. In order to use it, you must add the following node to your Android Manifest file, as a child of the
-<application> element:
<uses-library android:name="com.google.android.maps" />- diff --git a/docs/html/guide/topics/manifest/action-element.jd b/docs/html/guide/topics/manifest/action-element.jd deleted file mode 100644 index bc2e1d3..0000000 --- a/docs/html/guide/topics/manifest/action-element.jd +++ /dev/null @@ -1,46 +0,0 @@ -page.title=<action> -@jd:body - -
<action android:name="string" />
<intent-filter>-
<intent-filter> element must contain
-one or more {@code <action>} elements. If it doesn't contain any, no
-Intent objects will get through the filter. See
-Intents and
-Intent Filters for details on intent filters and the role of action
-specifications within a filter.
--For actions you define, it's best to use the package name as a prefix to -ensure uniqueness. For example, a {@code TRANSMOGRIFY} action might be specified -as follows: -
- -<action android:name="com.example.project.TRANSMOGRIFY" />-
<intent-filter><activity-alias android:enabled=["true" | "false"] - android:exported=["true" | "false"] - android:icon="drawable resource" - android:label="string resource" - android:name="string" - android:permission="string" - android:targetActivity="string" > - . . . -</activity-alias>
<application><intent-filter>
-<meta-data>
-The alias presents the target activity as a independent entity.
-It can have its own set of intent filters, and they, rather than the
-intent filters on the target activity itself, determine which intents
-can activate the target through the alias and how the system
-treats the alias. For example, the intent filters on the alias may
-specify the "{@link android.content.Intent#ACTION_MAIN
-android.intent.action.MAIN}"
-and "{@link android.content.Intent#CATEGORY_LAUNCHER
-android.intent.category.LAUNCHER}" flags, causing it to be
-represented in the application launcher, even though none of the
-filters on the target activity itself set these flags.
-
-With the exception of {@code targetActivity}, {@code <activity-alias>}
-attributes are a subset of <activity> attributes.
-For attributes in the subset, none of the values set for the target carry over
-to the alias. However, for attributes not in the subset, the values set for
-the target activity also apply to the alias.
-
-The <application> element has its own
-enabled attribute that applies to all
-application components, including activity aliases. The
-<application> and {@code <activity-alias>}
-attributes must both be "{@code true}" for the system to be able to instantiate
-the target activity through the alias. If either is "{@code false}", the alias
-does not work.
-
-The default value depends on whether the alias contains intent filters. The -absence of any filters means that the activity can be invoked through the alias -only by specifying the exact name of the alias. This implies that the alias -is intended only for application-internal use (since others would not know its name) -— so the default value is "{@code false}". -On the other hand, the presence of at least one filter implies that the alias -is intended for external use — so the default value is "{@code true}". -
<activity> element's
-icon attribute for more information.
-
-<activity> element's
-label attribute for more information.
-{@link android.content.Context#startActivity startActivity()} or
-{@link android.app.Activity#startActivityForResult startActivityForResult()}
-has not been granted the specified permission, the target activity will not be
-activated.
-
-This attribute supplants any permission set for the target activity itself. If -it is not set, a permission is not needed to activate the target through the alias. -
- --For more information on permissions, see the -Permissions -section in the introduction. -
<activity> element that precedes
-the alias in the manifest.
-<activity><activity android:allowTaskReparenting=["true" | "false"] - android:alwaysRetainTaskState=["true" | "false"] - android:clearTaskOnLaunch=["true"" | "false"] - android:configChanges=[one or more of: "mcc" "mnc" "locale" - "touchscreen" "keyboard" "keyboardHidden" - "navigation" "orientation" "fontScale"] - android:enabled=["true" | "false"] - android:excludeFromRecents=["true" | "false"] - android:exported=["true" | "false"] - android:finishOnTaskLaunch=["true" | "false"] - android:icon="drawable resource" - android:label="string resource" - android:launchMode=["multiple" | "singleTop" | - "singleTask" | "singleInstance"] - android:multiprocess=["true" | "false"] - android:name="string" - android:permission="string" - android:process="string" - android:screenOrientation=["unspecified" | "user" | "behind" | - "landscape" | "portrait" | - "sensor" | "nonsensor"] - android:stateNotNeeded=["true" | "false"] - android:taskAffinity="string" - android:theme="resource or theme" > - . . . -</activity>
<application><intent-filter>
-<meta-data>
-If this attribute is not set, the value set by the corresponding
-allowTaskReparenting
-attribute of the <application> element
-applies to the activity. The default value is "{@code false}".
-
-Normally when an activity is started, it's associated with the task of -the activity that started it and it stays there for its entire lifetime. -You can use this attribute to force it to be re-parented to the task it -has an affinity for when its current task is no longer displayed. -Typically, it's used to cause the activities of an application to move -to the main task associated with that application. -
- --For example, if an e-mail message contains a link to a web page, clicking -the link brings up an activity that can display the page. That activity -is defined by the browser application, but is launched as part of the e-mail -task. If it's reparented to the browser task, it will be shown when the -browser next comes to the front, and will be absent when the e-mail task -again comes forward. -
- -
-The affinity of an activity is defined by the
-taskAffinity attribute. The affinity
-of a task is determined by reading the affinity of its root activity.
-Therefore, by definition, a root activity is always in a task with the
-same affinity. Since activities with "{@code singleTask}" or
-"{@code singleInstance}" launch modes can only be at the root of a task,
-re-parenting is limited to the "{@code standard}" and "{@code singleTop}"
-modes. (See also the launchMode
-attribute.)
-
-Normally, the system clears a task (removes all activities from the stack -above the root activity) in certain situations when the user re-selects that -task from the home screen. Typically, this is done if the user hasn't visited -the task for a certain amount of time, such as 30 minutes. -
- --However, when this attribute is "{@code true}", users will always return -to the task in its last state, regardless of how they get there. This is -useful, for example, in an application like the web browser where there is -a lot of state (such as multiple open tabs) that users would not like to lose. -
-When the value is "{@code true}", every time users start the task again, they
-are brought to its root activity, regardless of what they were last doing in
-the task and regardless of whether they used BACK or HOME to last leave it.
-When the value is "{@code false}", the task may be cleared of activities in
-some situations (see the
-alwaysRetainTaskState attribute), but not always.
-
-Suppose, for example, that someone launches activity P from the home screen, -and from there goes to activity Q. The user next presses HOME, and then returns -to activity P. Normally, the user would see activity Q, since that is what they -were last doing in P's task. However, if P set this flag to "{@code true}", all -of the activities on top of it (Q in this case) were removed when the user pressed -HOME and the task went to the background. So the user sees only P when returning -to the task. -
- -
-If this attribute and allowTaskReparenting
-are both "{@code true}", any activities that can be re-parented are moved to
-the task they share an affinity with; the remaining activities are then dropped,
-as described above.
-
{@link android.app.Activity#onConfigurationChanged onConfigurationChanged()}
-method is called.
-
--Any or all of the following strings can be used to set this attribute. Values are -separated by '{@code |}' — for example, "{@code locale|navigation|orientation}". -
- -| Value | -Description | -
| "{@code mcc}" | -The IMSI mobile country code (MCC) has changed — - that is, a SIM has been detected and updated the MCC. | -
| "{@code mnc}" | -The IMSI mobile network code (MNC) has changed — - that is, a SIM has been detected and updated the MNC. | -
| "{@code locale}" | -The locale has changed — for example, the user has selected a new - language that text should be displayed in. | -
| "{@code touchscreen}" | -The touchscreen has changed. (This should never normally happen.) | -
| "{@code keyboard}" | -The keyboard type has changed — for example, the user has - plugged in an external keyboard. | -
| "{@code keyboardHidden}" | -The keyboard accessibility has changed — for example, the - user has slid the keyboard out to expose it. | -
| "{@code navigation}" | -The navigation type has changed. (This should never normally happen.) | -
| "{@code orientation}" | -The screen orientation has changed — that is, the user has rotated - the device. | -
| "{@code fontScale}" | -The font scaling factor has changed — that is, the user has selected - a new global font size. | -
-All of these configuration changes can impact the resource values seen by the
-application. Therefore, when {@link android.app.Activity#onConfigurationChanged
-onConfigurationChanged()} is called, it will generally be necessary to again
-retrieve all resources (including view layouts, drawables, and so on) to correctly
-handle the change.
-
-The <application> element has its own
-enabled attribute that applies to all
-application components, including activities. The
-<application> and {@code <activity>}
-attributes must both be "{@code true}" (as they both are by default) for
-the system to be able to instantiate the activity. If either is
-"{@code false}", it cannot be instantiated.
-
-The default value depends on whether the activity contains intent filters. The -absence of any filters means that the activity can be invoked only by specifying -its exact class name. This implies that the activity is intended only for -application-internal use (since others would not know the class name). So in -this case, the default value is "{@code false}". -On the other hand, the presence of at least one filter implies that the activity -is intended for external use, so the default value is "{@code true}". -
- -
-This attribute is not the only way to limit an activity's exposure to other
-applications. You can also use a permission to limit the external entities that
-can invoke the activity (see the permission
-attribute).
-
-If this attribute and allowTaskReparenting
-are both "{@code true}", this attribute trumps the other. The affinity of the
-activity is ignored. The activity is not re-parented, but destroyed.
-
-This attribute must be set as a reference to a drawable resource containing
-the image definition. If it is not set, the icon specified for the application
-as a whole is used instead (see the <application>
-element's icon attribute).
-
-The activity's icon — whether set here or by the
-<application> element — is also the
-default icon for all the activity's intent filters (see the
-<intent-filter> element's
-icon attribute).
-
-If this attribute is not set, the label set for the application as a whole is
-used instead (see the <application> element's
-label attribute).
-
-The activity's label — whether set here or by the
-<application> element — is also the
-default label for all the activity's intent filters (see the
-<intent-filter> element's
-label attribute).
-
-The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, -it can also be set as a raw string. -
"{@code standard}"
-
"{@code singleTop}"
-
"{@code singleTask}"
-
"{@code singleInstance}"
-The default mode is "{@code standard}". -
- -
-The modes fall into two main groups, with "{@code standard}" and
-"{@code singleTop}" activities on one side, and "{@code singleTask}" and
-"{@code singleInstance}" activities on the other. An activity with the
-"{@code standard}" or "{@code singleTop}" launch mode can be instantiated
-multiple times. The instances can belong to any task and can be located
-anywhere in the activity stack. Typically, they're launched into the task
-that called
-{@link android.content.Context#startActivity startActivity()}
-(unless the Intent object contains a
-{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}
-instruction, in which case a different task is chosen — see the
-taskAffinity attribute).
-
-In contrast, "{@code singleTask}" and "{@code singleInstance}" activities -can only begin a task. They are always at the root of the activity stack. -Moreover, the device can hold only one instance of the activity at a time -— only one such task. -
- -
-The "{@code standard}" and "{@code singleTop}" modes differ from each other
-in just one respect: Every time there's new intent for a "{@code standard}"
-activity, a new instance of the class is created to respond to that intent.
-Each instance handles a single intent.
-Similarly, a new instance of a "{@code singleTop}" activity may also be
-created to handle a new intent. However, if the target task already has an
-existing instance of the activity at the top of its stack, that instance
-will receive the new intent (in an
-{@link android.app.Activity#onNewIntent onNewIntent()} call);
-a new instance is not created.
-In other circumstances — for example, if an existing instance of the
-"{@code singleTop}" activity is in the target task, but not at the top of
-the stack, or if it's at the top of a stack, but not in the target task
-— a new instance would be created and pushed on the stack.
-
-The "{@code singleTask}" and "{@code singleInstance}" modes also differ from -each other in only one respect: A "{@code singleTask}" activity allows other -activities to be part of its task. It's at the root of the activity stack, -but other activities (necessarily "{@code standard}" and "{@code singleTop}" -activities) can be launched into the same task. A "{@code singleInstance}" -activity, on the other hand, permits no other activities to be part of its -task. It's the only activity in the task. If it starts another activity, -that activity is assigned to a different task — as if {@code -FLAG_ACTIVITY_NEW_TASK} was in the intent. -
- -For more information on launch modes and their interaction with Intent -flags, see the -Activities and -Tasks section of the -Application Fundamentals -document. -
--Normally, a new instance of an activity is launched into the process of the -application that defined it, so all instances of the activity run in the same -process. However, if this flag is set to "{@code true}", instances of the -activity can run in multiple processes, allowing the system to create instances -wherever they are used (provided permissions allow it), something that is almost -never necessary or desirable. -
<manifest>
-element.
-
--There is no default. The name must be specified. -
{@link android.content.Context#startActivity startActivity()} or
-{@link android.app.Activity#startActivityForResult startActivityForResult()}
-has not been granted the specified permission, its intent will not be
-delivered to the activity.
-
-
-If this attribute is not set, the permission set by the
-<application> element's
-permission attribute applies
-to the activity. If neither attribute is set, the activity is
-not protected by a permission.
-
-For more information on permissions, see the -Permissions -section in the introduction and another document, -Security and -Permissions. -
<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. -
| "{@code unspecified}" | -The default value. The system chooses the orientation. The policy it - uses, and therefore the choices made in specific contexts, may differ - from device to device. | -
| "{@code landscape}" | -Landscape orientation (the display is wider than it is tall). | -
| "{@code portrait}" | -Portrait orientation (the display is taller than it is wide). | -
| "{@code user}" | -The user's current preferred orientation. | -
| "{@code behind}" | -The same orientation as the activity that's immediately beneath it in - the activity stack. | -
| "{@code sensor}" | -The orientation determined by a physical orientation sensor. The - orientation of the display depends on how the user is holding the device; - it changes when the user rotates the device. | -
| "{@code nosensor}" | -An orientation determined without reference to a physical orientation sensor. - The sensor is ignored, so the display will not rotate based on how the user - moves the device. Except for this distinction, the system chooses the - orientation using the same policy as for the "{@code unspecified}" setting. | -
-Normally, before an activity is temporarily shut down to save resources, its
-{@link android.app.Activity#onSaveInstanceState onSaveInstanceState()}
-method is called. This method stores the current state of the activity in a
-{@link android.os.Bundle} object, which is then passed to
-{@link android.app.Activity#onCreate onCreate()} when the activity
-is restarted. If this attribute is set to "{@code true}",
-{@code onSaveInstanceState()} may not be called and {@code onCreate()} will
-be passed {@code null} instead of the Bundle — just as it was when the
-activity started for the first time.
-
-A "{@code true}" setting ensures that the activity can be restarted in the -absence of retained state. For example, the activity that displays the -home screen uses this setting to make sure that it does not get removed if it -crashes for some reason. -
-The affinity determines two things — the task that the activity is re-parented
-to (see the allowTaskReparenting
-attribute) and the task that will house the activity when it is launched
-with the {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}
-flag.
-
-By default, all activities in an application have the same affinity. You -can set this attribute to group them differently, and even place -activities defined in different applications within the same task. To -specify that the activity does not have an affinity for any task, set -it to an empty string. - -
-If this attribute is not set, the activity inherits the affinity set
-for the application (see the <application>
-element's taskAffinity attribute).
-The name of the default affinity for an application is the package name set
-by the <manifest> element.
-
{@link android.content.Context#setTheme setTheme()}, and may also
-cause "starting" animations prior to the activity being launched (to better
-match what the activity actually looks like).
-
-
-If this attribute is not set, the activity inherits the theme set for the
-application as a whole — see the <application>
-element's theme attribute. If that attribute is
-also not set, the default system theme is used.
-
<application android:allowClearUserData=["true" | "false"] - android:allowTaskReparenting=["true" | "false"] - android:debuggable=["true" | "false"] - android:description="string resource" - android:enabled=["true" | "false"] - android:hasCode=["true" | "false"] - android:icon="drawable resource" - android:label="string resource" - android:manageSpaceActivity="string" - android:name="string" - android:permission="string" - android:persistent=["true" | "false"] - android:process="string" - android:taskAffinity="string" - android:theme="resource or theme" > - . . . -</application>
<manifest><activity>
-<activity-alias>
-<service>
-<receiver>
-<provider>
-<uses-library>
-The
-<activity>
-element has its own
-allowTaskReparenting
-attribute that can override the value set here. See that attribute for more
-information.
-
-The default value is "{@code true}". -
-An application would not have any code of its own only if it's using nothing -but built-in component classes, such as an activity that uses the {@link -android.app.AliasActivity} class, a rare occurrence. - -
<activity>,
-<activity-alias>,
-<service>,
-<receiver>, and
-<provider> elements.
-
--This attribute must be set as a reference to a drawable resource containing -the image definition. There is no default icon. -
<activity>,
-<activity-alias>,
-<service>,
-<receiver>, and
-<provider> elements.
-
--The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, -it can also be set as a raw string. -
<activity> element.
--The subclass is optional; most applications won't need one. -In the absence of a subclass, Android uses an instance of the base -Application class. -
-For more information on permissions, see the -Permissions -section in the introduction and another document, -Security and -Permissions. -
-By default, Android creates a process for an application when the first
-of its components needs to run. All components then run in that process.
-The name of the default process matches the package name set by the
-<manifest> element.
-
By setting this attribute to a process name that's shared with another -application, you can arrange for components of both applications to run in -the same process — but only if the two applications also share a -user ID and be signed with the same certificate. -
- --If the name assigned to this attribute begins with a colon (':'), a new -process, private to the application, is created when it's needed. -If the process name begins with a lowercase character, a global process -of that name is created. A global process can be shared with other -applications, reducing resource usage. -
taskAffinity
-attributes. See that attribute for more information.
-
-
-By default, all activities within an application share the same
-affinity. The name of that affinity is the same as the package name
-set by the
-<manifest> element.
-
theme
-attributes; see that attribute for more information.<activity>
-<service>
-<receiver>
-<provider><category android:name="string" />
<intent-filter>-Custom categories should use the package name as a prefix, to ensure -that they are unique. -
<action>
-<data><data android:host="string" - android:mimeType="string" - android:path="string" - android:pathPattern="string" - android:pathPrefix="string" - android:port="string" - android:scheme="string" />
<intent-filter>mimeType attribute),
-just a URI, or both a data type and a URI. A URI is specified by separate
-attributes for each of its parts:
-
-{@code scheme://host:port/path} or -{@code pathPrefix} or {@code pathPattern}
- -
-These attributes are optional, but also mutually dependent:
-If a scheme is not specified for the
-intent filter, all the other URI attributes are ignored. If a
-host is not specified for the filer,
-the {@code port} attribute and all the path attributes are ignored.
-
-All the {@code <data>} elements contained within the same
-<intent-filter> element contribute to
-the same filter. So, for example, the following filter specification,
-
<intent-filter . . . > - <data android:scheme="something" android:host="project.example.com" /> - . . . -</intent-filter>- -
is equivalent to this one:
- -<intent-filter . . . > - <data android:scheme="something" /> - <data android:host="project.example.com" /> - . . . -</intent-filter>- -
-You can place any number of <data> elements inside an
-<intent-filter> to give it multiple data
-options. None of its attributes have default values.
-
-Information on how intent filters work, including the rules for how Intent objects -are matched against filters, can be found in another document, -Intents and -Intent Filters. See also the -Intent Filters -section in the introduction. -
scheme attribute is also
-specified for the filter.
--Because '{@code \}' is used as an escape character when the string is read -from XML (before it is parsed as a pattern), you will need to double-escape: -For example, a literal '{@code *}' would be written as "{@code \\*}" and a -literal '{@code \}' would be written as "{@code \\\\}". This is basically -the same as what you would need to write if constructing the string in Java code. -
- --For more information on these three types of patterns, see the descriptions of -{@link android.os.PatternMatcher#PATTERN_LITERAL}, -{@link android.os.PatternMatcher#PATTERN_PREFIX}, and -{@link android.os.PatternMatcher#PATTERN_SIMPLE_GLOB} in the -{@link android.os.PatternMatcher} class. -
- -These attributes are meaningful only if the
-scheme and host
-attributes are also specified for the filter.
-
scheme and
-host attributes are also specified for
-the filter.-A scheme is specified without the trailing colon (for example, -{@code http}, rather than {@code http:}). -
- -
-If the filter has a data type set (the mimeType
-attribute) but no scheme, the {@code content:} and {@code file:} schemes are
-assumed.
-
<action>
-<category><grant-uri-permission android:path="string" - android:pathPattern="string" - android:pathPrefix="string" />
<provider>
-If a content provider's grantUriPermissions
-attribute is "{@code true}", permission can be granted for any the data under
-the provider's purview. However, if that attribute is "{@code false}", permission
-can be granted only to data subsets that are specified by this element.
-A provider can contain any number of {@code <grant-uri-permission>} elements.
-Each one can specify only one path (only one of the three possible attributes).
-
-For information on how permission is granted, see the
-<intent-filter> element's
-grantUriPermissions attribute.
-
A period followed by an asterisk ("{@code .*}") matches any sequence of -0 to many characters.
-Because '{@code \}' is used as an escape character when the string is read -from XML (before it is parsed as a pattern), you will need to double-escape: -For example, a literal '{@code *}' would be written as "{@code \\*}" and a -literal '{@code \}' would be written as "{@code \\\\}". This is basically -the same as what you would need to write if constructing the string in Java code. -
- --For more information on these types of patterns, see the descriptions of -{@link android.os.PatternMatcher#PATTERN_LITERAL}, -{@link android.os.PatternMatcher#PATTERN_PREFIX}, and -{@link android.os.PatternMatcher#PATTERN_SIMPLE_GLOB} in the -{@link android.os.PatternMatcher} class. -
grantUriPermissions
-attribute of the
-<provider>
-element<instrumentation android:functionalTest=["true" | "false"] - android:handleProfiling=["true" | "false"] - android:icon="drawable resource" - android:label="string resource" - android:name="string" - android:targetPackage="string" />
<manifest><manifest> element.
-
--There is no default. The name must be specified. -
<manifest> element.<intent-filter android:icon="drawable resource" - android:label="string resource" - android:priority="integer" > - . . . -</intent-filter>
<activity>
-<activity-alias>
-<service>
-<receiver><action><category>
-<data>
-Most of the contents of the filter are described by its
-<action>,
-<category>, and
-<data> subelements.
-
-For a more detailed discussion of filters, see the separate -Intents -and Intent Filters document, as well as the -Intents Filters -section in the introduction. -
-This attribute must be set as a reference to a drawable resource
-containing the image definition. The default value is the icon set
-by the parent component's {@code icon} attribute. If the parent
-does not specify an icon, the default is the icon set by the
-<application> element.
-
-For more on intent filter icons, see -Icons and Labels -in the introduction. -
-The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, -it can also be set as a raw string. -
- -
-The default value is the label set by the parent component. If the
-parent does not specify a label, the default is the label set by the
-<application> element's
- label attribute.
-
-For more on intent filter labels, see -Icons and Labels -in the introduction. -
It controls the order in which broadcast receivers are executed to -receive broadcast messages. Those with higher priority -values are called before those with lower values. (The order applies only -to synchronous messages; it's ignored for asynchronous messages.)
-Use this attribute only if you really need to impose a specific order in -which the broadcasts are received, or want to force Android to prefer -one activity over others. -
- --The value must be an integer, such as "{@code 100}". Higher numbers have a -higher priority. -
<action>
-<category>
-<data><manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="string" - android:sharedUserId="string" - android:versionCode="integer" - android:versionName="string" > - . . . -</manifest>
-
-
-
<application><instrumentation>
-<permission>
-<permission-group>
-<permission-tree>
-<uses-permission>-
<application> element
-and specify {@code xlmns:android} and {@code package} attributes.com.google.app.application_name.
-
-
-The package name serves as a unique identifier for the application.
-It's also the default name for the application process (see the
-<application>
-element's
-process
-process attribute) and the default task affinity of an activity
-(see the
-<activity>
-element's
-taskAffinity attribute).
-
-The value must be set as an integer, such as "100". You can define it however -you want, as long as each successive version has a higher number. For example, -it could be a build number. Or you could translate a version number in "x.y" -format to an integer by encoding the "x" and "y" separately in the lower and -upper 16 bits. Or you could simply increase the number by one each time a new -version is released. -
-
<application>-Every application must have an AndroidManifest.xml file (with precisely that -name) in its root directory. The manifest presents essential information about -the application to the Android system, information the system must have before -it can run any of the application's code. Among other things, the manifest -does the following: -
- --The diagram below shows the general structure of the manifest file and -every element that it can contain. Each element, along with all of its -attributes, is documented in full in a separate file. To view detailed -information about any element, click on the element name in the diagram, -in the alphabetical list of elements that follows the diagram, or on any -other mention of the element name. -
- --<?xml version="1.0" encoding="utf-8"?> - -<manifest> - - <uses-permission /> - <permission /> - <permission-tree /> - <permission-group /> - - <instrumentation /> - - <uses-sdk /> - - <application> - - <activity> - <intent-filter> - <action /> - <category /> - <data /> - </intent-filter> - <meta-data /> - </activity> - - <activity-alias> - <intent-filter> . . . </intent-filter> - <meta-data /> - </activity-alias> - - <service> - <intent-filter> . . . </intent-filter> - <meta-data/> - </service> - - <receiver> - <intent-filter> . . . </intent-filter> - <meta-data /> - </receiver> - - <provider> - <grant-uri-permission /> - <meta-data /> - </provider> - - <uses-library /> - - </application> - -</manifest> -- -
-All the elements that can appear in the manifest file are listed below -in alphabetical order. These are the only legal elements; you cannot -add your own elements or attributes. -
- -
-<action>
-<activity>
-<activity-alias>
-<application>
-<category>
-<data>
-<grant-uri-permission>
-<instrumentation>
-<intent-filter>
-<manifest>
-<meta-data>
-<permission>
-<permission-group>
-<permission-tree>
-<provider>
-<receiver>
-<service>
-<uses-library>
-<uses-permission>
-<uses-sdk>
-
-Some conventions and rules apply generally to all elements and attributes -in the manifest: -
- -<manifest> and
-<application>
-elements are required, they each must be present and can occur only once.
-Most of the others can occur many times or not at all — although at
-least some of them must be present for the manifest to accomplish anything
-meaningful.
-
--If an element contains anything at all, it contains other elements. -All values are set through attributes, not as character data within an element. -
- -
-Elements at the same level are generally not ordered. For example,
-<activity>,
-<provider>, and
-<service>
-elements can be intermixed in any sequence. (An
-<activity-alias>
-element is the exception to this rule: It must follow the
-<activity>
-it is an alias for.)
-
Except for some attributes of the root
-<manifest>
-element, all attribute names begin with an {@code android:} prefix —
-for example, {@code android:alwaysRetainTaskState}. Because the prefix is
-universal, the documentation generally omits it when referring to attributes
-by name.
<application>
-element) and its principal components — activities
-(<activity>),
-services
-(<service>),
-broadcast receivers
-(<receiver>),
-and content providers
-(<provider>).
-
--If you define a subclass, as you almost always would for the component classes -({@link android.app.Activity}, {@link android.app.Service}, -{@link android.content.BroadcastReceiver}, and {@link android.content.ContentProvider}), -the subclass is declared through a {@code name} attribute. The name must include -the full package designation. -For example, an {@link android.app.Service} subclass might be declared as follows: -
- -<manifest . . . > - <application . . . > - <service android:name="com.example.project.SecretService" . . . > - . . . - </service> - . . . - </application> -</manifest>- -
-However, as a shorthand, if the first character of the string is a period, the
-string is appended to the application's package name (as specified by the
-<manifest>
-element's
-package
-attribute). The following assignment is the same as the one above:
-
<manifest package="com.example.project" . . . > - <application . . . > - <service android:name=".SecretService" . . . > - . . . - </service> - . . . - </application> -</manifest>- -
-When starting a component, Android creates an instance of the named subclass. -If a subclass isn't specified, it creates an instance of the base class. -
<intent-filter . . . > - <action android:name="android.intent.action.EDIT" /> - <action android:name="android.intent.action.INSERT" /> - <action android:name="android.intent.action.DELETE" /> - . . . -</intent-filter>
{@code @[package:]type:name}
- --where the package name can be omitted if the resource is in the same package -as the application, type is a type of resource — such as "string" or -"drawable" — and name is the name that identifies the specific resource. -For example: -
- -<activity android:icon="@drawable/smallPic" . . . >- -
-Values from a theme are expressed in a similar manner, but with an initial '{@code ?}' -rather than '{@code @}': -
- -{@code ?[package:]type:name} -
-The following sections describe how some Android features are reflected -in the manifest file. -
- - --The core components of an application (its activities, services, and broadcast -receivers) are activated by intents. An intent is a -bundle of information (an {@link android.content.Intent} object) describing a -desired action — including the data to be acted upon, the category of -component that should perform the action, and other pertinent instructions. -Android locates an appropriate component to respond to the intent, launches -a new instance of the component if one is needed, and passes it the -Intent object. -
- -
-Components advertise their capabilities — the kinds of intents they can
-respond to — through intent filters. Since the Android system
-must learn which intents a component can handle before it launches the component,
-intent filters are specified in the manifest as
-<intent-filter>
-elements. A component may have any number of filters, each one describing
-a different capability.
-
-An intent that explicitly names a target component will activate that component; -the filter doesn't play a role. But an intent that doesn't specify a target by -name can activate a component only if it can pass through one of the component's -filters. -
- --For information on how Intent objects are tested against intent filters, -see a separate document, -Intents -and Intent Filters. -
- - -
-A number of elements have {@code icon} and {@code label} attributes for a
-small icon and a text label that can be displayed to users. Some also have a
-{@code description} attribute for longer explanatory text that can also be
-shown on-screen. For example, the
-<permission>
-element has all three of these attributes, so that when the user is asked whether
-to grant the permission to an application that has requested it, an icon representing
-the permission, the name of the permission, and a description of what it
-entails can all be presented to the user.
-
-In every case, the icon and label set in a containing element become the default
-{@code icon} and {@code label} settings for all of the container's subelements.
-Thus, the icon and label set in the
-<application>
-element are the default icon and label for each of the application's components.
-Similarly, the icon and label set for a component — for example, an
-<activity>
-element — are the default settings for each of the component's
-<intent-filter>
-elements. If an
-<application>
-element sets a label, but an activity and its intent filter do not,
-the application label is treated as the label for both the activity and
-the intent filter.
-
-The icon and label set for an intent filter are used to represent a component -whenever the component is presented to the user as fulfilling the function -advertised by the filter. For example, a filter with -"{@code android.intent.action.MAIN}" and -"{@code android.intent.category.LAUNCHER}" settings advertises an activity -as one that initiates an application — that is, as -one that should be displayed in the application launcher. The icon and label -set in the filter are therefore the ones displayed in the launcher. -
- - --A permission is a restriction limiting access to a part of the code -or to data on the device. The limitation is imposed to protect critical -data and code that could be misused to distort or damage the user experience. -
- --Each permission is identified by a unique label. Often the label indicates -the action that's restricted. For example, here are some permissions defined -by Android: -
- -{@code android.permission.CALL_EMERGENCY_NUMBERS}
-
{@code android.permission.READ_OWNER_DATA}
-
{@code android.permission.SET_WALLPAPER}
-
{@code android.permission.DEVICE_POWER}
-A feature can be protected by at most one permission. -
- -
-If an application needs access to a feature protected by a permission,
-it must declare that it requires that permission with a
-<uses-permission>
-element in the manifest. Then, when the application is installed on
-the device, the installer determines whether or not to grant the requested
-permission by checking the authorities that signed the application's
-certificates and, in some cases, asking the user.
-If the permission is granted, the application is able to use the protected
-features. If not, its attempts to access those features will simply fail
-without any notification to the user.
-
-An application can also protect its own components (activities, services,
-broadcast receivers, and content providers) with permissions. It can employ
-any of the permissions defined by Android (listed in
-{@link android.Manifest.permission android.Manifest.permission}) or declared
-by other applications. Or it can define its own. A new permission is declared
-with the
-<permission>
-element. For example, an activity could be protected as follows:
-
-<manifest . . . > - <permission android:name="com.example.project.DEBIT_ACCT" . . . /> - . . . - <application . . .> - <activity android:name="com.example.project.FreneticActivity" . . . > - android:permission="com.example.project.DEBIT_ACCT" - . . . > - . . . - </activity> - </application> - . . . - <uses-permission android:name="com.example.project.DEBIT_ACCT" /> - . . . -</manifest> -- -
-Note that, in this example, the {@code DEBIT_ACCT} permission is not only
-declared with the
-<permission>
-element, its use is also requested with the
-<uses-permission>
-element. Its use must be requested in order for other components of the
-application to launch the protected activity, even though the protection
-is imposed by the application itself.
-
-If, in the same example, the {@code permission} attribute was set to a
-permission declared elsewhere
-(such as {@code android.permission.CALL_EMERGENCY_NUMBERS}, it would not
-have been necessary to declare it again with a
-<permission>
-element. However, it would still have been necessary to request its use with
-<uses-permission>.
-
-The
-<permission-tree>
-element declares a namespace for a group of permissions that will be defined in
-code. And
-<permission-group>
-defines a label for a set of permissions (both those declared in the manifest with
-<permission>
-elements and those declared elsewhere). It affects only how the permissions are
-grouped when presented to the user. The
-<permission-group>
-element does not specify which permissions belong to the group;
-it just gives the group a name. A permission is placed in the group
-by assigning the group name to the
-<permission>
-element's
-permissionGroup
-attribute.
-
-Every application is linked against the default Android library, which -includes the basic packages for building applications (with common classes -such as Activity, Service, Intent, View, Button, Application, ContentProvider, -and so on). -
- -
-However, some packages reside in their own libraries. If your application
-uses code from any of these packages, it must explicitly asked to be linked
-against them. The manifest must contain a separate
-<uses-library>
-element to name each of the libraries. (The library name can be found in the
-documentation for the package.)
-
<meta-data android:name="string" - android:resource="resource specification" - android:value="string" />
<activity>
-<activity-alias>
-<service>
-<receiver>
-Ordinary values are specified through the value
-attribute. However, to assign a resource ID as the value, use the
-resource attribute instead. For example,
-the following code assigns whatever value is stored in the {@code @string/kangaroo}
-resource to the "{@code zoo}" name:
-
<meta-data android:name="zoo" android:value="@string/kangaroo" />- -
-On the other hand, using the {@code resource} attribute would assign "{@code zoo}" -the numeric ID of the resource, not the value stored in the resource: -
- -<meta-data android:name="zoo" android:resource="@string/kangaroo" />- -
-It is highly recommended that you avoid supplying related data as -multiple separate {@code <meta-data>} entries. Instead, if you -have complex data to associate with a component, store it as a resource and -use the {@code resource} attribute to inform the component of its ID. -
| Type | -Bundle method | -
|---|---|
| String value, using double backslashes ({@code \\}) to escape characters - — such as "{@code \\n}" and "{@code \\uxxxxx}" for a Unicode character. | -{@link android.os.Bundle#getString(String) getString()} | -
| Integer value, such as "{@code 100}" | -{@link android.os.Bundle#getInt(String) getInt()} | -
| Boolean value, either "{@code true}" or "{@code false}" | -{@link android.os.Bundle#getBoolean(String) getBoolean()} | -
| Color value, in the form "{@code #rgb}", "{@code #argb}", - "{@code #rrggbb}", or "{@code #aarrggbb}" | -{@link android.os.Bundle#getString(String) getString()} | -
| Float value, such as "{@code 1.23}" | -{@link android.os.Bundle#getFloat(String) getFloat()} | -
<permission android:description="string resource" - android:icon="drawable resource" - android:label="string resource" - android:name="string" - android:permissionGroup="string" - android:protectionLevel=["normal" | "dangerous" | - "signature" | "signatureOrSystem"] />
<manifest>-This attribute must be set as a reference to a string resource; -unlike the {@code label} attribute, it cannot be a raw string. -
-As a convenience, the label can be directly set -as a raw string while you're developing the application. However, -when the application is ready to be published, it should be set as a -reference to a string resource, so that it can be localized like other -strings in the user interface. -
<uses-permission> element and the
-{@code permission} attributes of application components.
-
--The name must be unique, so it should use Java-style scoping — -for example, "{@code com.example.project.PERMITTED_ACTION}". -
<permission-group> element in this
-or another application. If this attribute is not set, the permission
-does not belong to a group.| Value | -Meaning | -
|---|---|
| "{@code normal}" | -The default value. A lower-risk permission that gives requesting - applications access to isolated application-level features, with - minimal risk to other applications, the system, or the user. - The system automatically grants this type - of permission to a requesting application at installation, without - asking for the user's explicit approval (though the user always - has the option to review these permissions before installing). - |
| "{@code dangerous}" | -A higher-risk permission that would give a requesting application - access to private user data or control over the device that can - negatively impact the user. Because this type of permission - introduces potential risk, the system may not automatically - grant it to the requesting application. For example, any dangerous - permissions requested by an application may be displayed to the - user and require confirmation before proceeding, or some other - approach may be taken to avoid the user automatically allowing - the use of such facilities. - |
| "{@code signature}" | -A permission that the system grants only if the requesting - application is signed with the same certificate as the application - that declared the permission. If the certificates match, the system - automatically grants the permission without notifying the user or - asking for the user's explicit approval. - |
| "{@code signatureOrSystem}" | -A permission that the system grants only to applications that are - in the Android system image or that are signed with the same - certificates as those in the system image. Please avoid using this - option, as the {@code signature} protection level should be sufficient - for most needs and works regardless of exactly where applications are - installed. The "{@code signatureOrSystem}" - permission is used for certain special situations where multiple - vendors have applications built into a system image and need - to share specific features explicitly because they are being built - together. - |
<uses-permission>
-<permission-tree>
-<permission-group><permission-group android:description="string resource" - android:icon="drawable resource" - android:label="string resource" - android:name="string" />
<manifest><permission> element. Members of a group are
-presented together in the user interface.
-
-
-Note that this element does not declare a permission itself, only a category in
-which permissions can be placed. See the
-<permission> element for element for information
-on declaring permissions and assigning them to groups.
-
<permission>
-element's
-<permissionGroup>
-attribute.<permission>
-<permission-tree>
-<uses-permission><permission-tree android:icon="drawable resource" - android:label="string resource" ] - android:name="string" />
<manifest>{@link android.content.pm.PackageManager#addPermission PackageManager.addPermission()}. Names within the tree are separated by
-periods ('{@code .}'). For example, if the base name is
-{@code com.example.project.taxes}, permissions like the following might be
-added:
-
-{@code com.example.project.taxes.CALCULATE}
-
{@code com.example.project.taxes.deductions.MAKE_SOME_UP}
-
{@code com.example.project.taxes.deductions.EXAGGERATE}
-Note that this element does not declare a permission itself, only a
-namespace in which further permissions can be placed. See the
-<permission>
-element for information on declaring permissions.
-
-
-
<permission>
-<permission-group>
-<uses-permission>
-<provider android:authorities="list" - android:enabled=["true" | "false"] - android:exported=["true" | "false"] - android:grantUriPermissions=["true" | "false"] - android:icon="drawable resource" - android:initOrder="integer" - android:label="string resource" - android:multiprocess=["true" | "false"] - android:name="string" - android:permission="string" - android:process="string" - android:readPermission="string" - android:syncable=["true" | "false"] - android:writePermission="string" > - . . . -</provider>
<application><meta-data>
-<grant-uri-permission>
-The Android system identifies content providers by the authority part
- of a {@code content:} URI. For example, suppose that the following URI
-is passed to {@link android.content.ContentResolver#query
-ContentResolver.query()}:
-
-
{@code content://com.example.project.healthcareprovider/nurses/rn}
- --The {@code content:} scheme identifies the data as belonging to a content -provider and the authority ({@code com.example.project.healthcareprovider}) -identifies the particular provider. The authority therefore must be unique. -Typically, as in this example, it's the fully qualified name of a -ContentProvider subclass. The path part of a URI may be used by a content -provider to identify particular data subsets, but those paths are not -declared in the manifest. -
- --For information on using and developing content providers, see a separate document, -Content Providers. -
-There is no default. At least one authority must be specified. -
-The <application> element has its own
-enabled attribute that applies to all
-application components, including content providers. The
-<application> and {@code <provider>}
-attributes must both be "{@code true}" (as they both
-are by default) for the content provider to be enabled. If either is
-"{@code false}", the provider is disabled; it cannot be instantiated.
-
-You can export a content provider but still limit access to it with the
-permission attribute.
-
readPermission,
-writePermission, and
-permission attributes
-—
-"{@code true}" if permission can be granted, and "{@ code false}" if not.
-If "{@code true}", permission can be granted to any of the content
-provider's data. If "{@code false}", permission can be granted only
-to the data subsets listed in
-<grant-uri-permission> subelements,
-if any. The default value is "{@code false}".
-
--Granting permission is a way of giving an application component one-time -access to data protected by a permission. For example, when an e-mail -message contains an attachment, the mail application may call upon the -appropriate viewer to open it, even though the viewer doesn't have general -permission to look at all the content provider's data. -
- -
-In such cases, permission is granted by
-{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION}
-and {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION}
-flags in the Intent object that activates the component. For example, the
-mail application might put {@code FLAG_GRANT_READ_URI_PERMISSION} in the
-Intent passed to {@code Context.startActivity()}. The permission is specific
-to the URI in the Intent.
-
-If you enable this feature, either by setting this attribute to "{@code true}"
-or by defining <grant-uri-permission>
-subelements, you must call
-{@link android.content.Context#revokeUriPermission
-Context.revokeUriPermission()} when a covered URI is deleted from
-the provider.
-
-See also the <grant-uri-permission>
-element.
-
<application>
-element's icon attribute).<application> element's
-label attribute).
-
--The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, -it can also be set as a raw string. -
-Normally, a content provider is instantiated in the process of the -application that defined it. However, if this flag is set to "{@code true}", -the system can create an instance in every process where there's a client -that wants to interact withit, thus avoiding the overhead of interprocess -communication. -
<manifest> element.
-
--There is no default. The name must be specified. -
readPermission and
-writePermission attributes take precedence
-over this one. If the readPermission
-attribute is also set, it controls access for querying the content provider.
-And if the writePermission attribute is set,
-it controls access for modifying the provider's data.
-
--For more information on permissions, see the -Permissions -section in the introduction and a separate document, -Security and -Permissions. -
<application> element's
-process
-attribute can set a different
-default for all components. But each component can override the default
-with its own {@code process} attribute, 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. -
permission and
-writePermission attributes.permission and
-readPermission attributes.-
<receiver android:enabled=["true" | "false"] - android:exported=["true" | "false"] - android:icon="drawable resource" - android:label="string resource" - android:name="string" - android:permission="string" - android:process="string" > - . . . -</receiver>
<application><intent-filer>
-<meta-data>
-There are two ways to make a broadcast receiver known to the system: One is
-declare it in the manifest file with this element. The other is to create
-the receiver dynamically in code and register it with the {@link
-android.content.Context#registerReceiver Context.registerReceiver()}
-method. See the {@link android.content.BroadcastReceiver} class description
-for more on dynamically created receivers.
-
-The <application> element has its own
-enabled attribute that applies to all
-application components, including broadcast receivers. The
-<application> and
-{@code <receiver>} attributes must both be "{@code true}" for
-the broadcast receiver to be enabled. If either is "{@code false}", it is
-disabled; it cannot be instantiated.
-
-The default value depends on whether the broadcast receiver contains intent filters. -The absence of any filters means that it can be invoked only by Intent objects that -specify its exact class name. This implies that the receiver is intended only for -application-internal use (since others would not normally know the class name). -So in this case, the default value is "{@code false}". -On the other hand, the presence of at least one filter implies that the broadcast -receiver is intended to receive intents broadcast by the system or other applications, -so the default value is "{@code true}". -
- -
-This attribute is not the only way to limit a broadcast receiver's external exposure.
-You can also use a permission to limit the external entities that can send it messages
-(see the permission attribute).
-
<application>
-element's icon attribute).
-
-
-The broadcast receiver's icon — whether set here or by the
-<application> element — is also the
-default icon for all the receiver's intent filters (see the
-<intent-filter> element's
-icon attribute).
-
<application> element's
-label attribute).
-
-
-The broadcast receiver's label — whether set here or by the
-<application> element — is also the
-default label for all the receiver's intent filters (see the
-<intent-filter> element's
-label attribute).
-
-The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, -it can also be set as a raw string. -
<manifest> element.
-
--There is no default. The name must be specified. -
<application> element's
-permission attribute applies
-to the broadcast receiver. If neither attribute is set, the receiver
-is not protected by a permission.
-
--For more information on permissions, see the -Permissions -section in the introduction and a separate document, -Security and Permissions. -
<application> element's
-process attribute can set a different
-default for all components. But each component can override the default
-with its own {@code process} attribute, 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 broadcast receiver runs in that process. -If the process name begins with a lowercase character, the receiver 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. -
<service android:enabled=["true" | "false"] - android:exported[="true" | "false"] - android:icon="drawable resource" - android:label="string resource" - android:name="string" - android:permission="string" - android:process="string" > - . . . -</service>
<application><intent-filer>
-<meta-data>-All services must be represented by {@code <service>} elements in -the manifest file. Any that are not declared there will not be seen -by the system and will never be run. -
-The <application> element has its own
-enabled attribute that applies to all
-application components, including services. The
-<application> and {@code <service>}
-attributes must both be "{@code true}" (as they both
-are by default) for the service to be enabled. If either is
-"{@code false}", the service is disabled; it cannot be instantiated.
-
-The default value depends on whether the service contains intent filters. The -absence of any filters means that it can be invoked only by specifying -its exact class name. This implies that the service is intended only for -application-internal use (since others would not know the class name). So in -this case, the default value is "{@code false}". -On the other hand, the presence of at least one filter implies that the service -is intended for external use, so the default value is "{@code true}". -
- -
-This attribute is not the only way to limit the exposure of a service to other
-applications. You can also use a permission to limit the external entities that
-can interact with the service (see the permission
-attribute).
-
<application>
-element's icon attribute).
-
-
-
-The service's icon — whether set here or by the
-<application> element — is also the
-default icon for all the service's intent filters (see the
-<intent-filter> element's
-icon attribute).
-
<application> element's
-label attribute).
-
-
-The service's label — whether set here or by the
-<application> element — is also the
-default label for all the service's intent filters (see the
-<intent-filter> element's
-label attribute).
-
-The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, -it can also be set as a raw string. -
<manifest> element.
-
--There is no default. The name must be specified. -
{@link android.content.Context#startService startService()},
-{@link android.content.Context#bindService bindService()}, or
-{@link android.content.Context#stopService stopService()},
-has not been granted this permission, the method will not work and the
-Intent object will not be delivered to the service.
-
-
-If this attribute is not set, the permission set by the
-<application> element's
-permission
-attribute applies to the service. If neither attribute is set, the service is
-not protected by a permission.
-
-For more information on permissions, see the -Permissions -section in the introduction and a separate document, -Security and Permissions. -
<application> element's
-process
-attribute can set a different
-default for all components. But component can override the default
-with its own {@code process} attribute, 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 service runs in that process. -If the process name begins with a lowercase character, the service 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. -
<application>
-<activity><uses-library android:name="string" />
<application>-All of the {@code android} packages (such as {@link android.app}, -{@link android.content}, {@link android.view}, and {@link android.widget}) -are in the default library that all applications are automatically linked -against. However, some packages (such as {@code maps} and {@code awt} are -in separate libraries that are not automatically linked. Consult the -documentation for the packages you're using to determine which library -contains the package code. -
<uses-permission android:name="string" />
<manifest>-For more information on permissions, see the -Permissions -section in the introduction and the separate -Security and Permissions document. -A list of permissions defined by the base platform can be found at -{@link android.Manifest.permission android.Manifest.permission}. - -
<permission>
-element, a permission defined by another application, or one of the
-standard system permissions, such as "{@code android.permission.CAMERA}"
-or "{@code android.permission.READ_CONTACTS}". As these examples show,
-a permission name typically includes the package name as a prefix.<permission><uses-sdk android:minSdkVersion="integer" />
<manifest>-The default level is 1. -
- --For more information on the API level, see the -Specifying -Minimum System API Version section of -Versioning Your -Applications. -
-Despite its name, this attribute is set to the API level, not to the -version number of the SDK (software development kit). The API level is always -a single integer; the SDK version may be split into major and minor components -(such as 1.2). You cannot derive the API level from the SDK version number -(for example, it is not the same as the major version or the sum of the major -and minor versions). To learn what the API level is, check the notes that -came with the SDK you're using. -
The Android platform offers built-in encoding/decoding for a variety of -common media types, so that you can easily integrate audio, video, and images into your -applications. Accessing the platform's media capabilities is fairly straightforward -— you do so using the same intents and activities mechanism that the rest of -Android uses.
- -Android lets you play audio and video from several types of data sources. You -can play audio or video from media files stored in the application's resources -(raw resources), from standalone files in the filesystem, or from a data stream -arriving over a network connection. To play audio or video from your -application, use the {@link android.media.MediaPlayer} class.
- -The platform also lets you record audio, where supported by the mobile device -hardware. Recording of video is not currently supported, but is planned for a -future release. To record audio, use the -{@link android.media.MediaRecorder} class. Note that the emulator doesn't have -hardware to capture audio, but actual mobile devices are likely to provide these -capabilities that you can access through MediaRecorder.
- -For a list of the media formats for which Android offers built-in support, -see the Android Media -Formats appendix.
- -Media can be played from anywhere: from a raw resource, from a file from the system, -or from an available network (URL).
- -You can play back the audio data only to the standard -output device; currently, that is the mobile device speaker or Bluetooth headset. You -cannot play sound files in the conversation audio.
- -Perhaps the most common thing to want to do is play back media (notably sound) -within your own applications. Doing this is easy:
-res/raw
- folder of your project, where the Eclipse plugin (or aapt) will find it and
- make it into a resource that can be referenced from your R classMediaPlayer, referencing that resource using
- {@link android.media.MediaPlayer#create MediaPlayer.create}, and then call
- {@link android.media.MediaPlayer#start() start()} on the instance:- MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); - mp.start(); --
To stop playback, call {@link android.media.MediaPlayer#stop() stop()}. If
-you wish to later replay the media, then you must
-{@link android.media.MediaPlayer#reset() reset()} and
-{@link android.media.MediaPlayer#prepare() prepare()} the MediaPlayer object
-before calling {@link android.media.MediaPlayer#start() start()} again.
-(create() calls prepare() the first time.)
To pause playback, call {@link android.media.MediaPlayer#pause() pause()}. -Resume playback from where you paused with -{@link android.media.MediaPlayer#start() start()}.
- -You can play back media files from the filesystem or a web URL:
-MediaPlayer using new- MediaPlayer mp = new MediaPlayer(); - mp.setDataSource(PATH_TO_FILE); - mp.prepare(); - mp.start(); --
{@link android.media.MediaPlayer#stop() stop()} and -{@link android.media.MediaPlayer#pause() pause()} work the same as discussed -above.
-Note: It is possible that mp could be
- null, so good code should null check after the new.
- Also, IllegalArgumentException and IOException either
- need to be caught or passed on when using setDataSource(), since
- the file you are referencing may not exist.
Note: -If you're passing a URL to an online media file, the file must be capable of -progressive download.
- -Audio capture from the device is a bit more complicated than audio/video playback, but still fairly simple:
-newTITLE, TIMESTAMP, and the all important
- MIME_TYPEMediaRecorder.AudioSource.MICThe example below illustrates how to set up, then start audio capture.
-
- recorder = new MediaRecorder();
- ContentValues values = new ContentValues(3);
-
- values.put(MediaStore.MediaColumns.TITLE, SOME_NAME_HERE);
- values.put(MediaStore.MediaColumns.TIMESTAMP, System.currentTimeMillis());
- values.put(MediaStore.MediaColumns.MIME_TYPE, recorder.getMimeContentType());
-
- ContentResolver contentResolver = new ContentResolver();
-
- Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
- Uri newUri = contentResolver.insert(base, values);
-
- if (newUri == null) {
- // need to handle exception here - we were not able to create a new
- // content entry
- }
-
- String path = contentResolver.getDataFilePath(newUri);
-
- // could use setPreviewDisplay() to display a preview to suitable View here
-
- recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
- recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
- recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
- recorder.setOutputFile(path);
-
- recorder.prepare();
- recorder.start();
-
-Based on the example above, here's how you would stop audio capture.
-- recorder.stop(); - recorder.release(); -- diff --git a/docs/html/guide/topics/media/media.jd b/docs/html/guide/topics/media/media.jd deleted file mode 100644 index 463686d..0000000 --- a/docs/html/guide/topics/media/media.jd +++ /dev/null @@ -1,172 +0,0 @@ -page.title=Media Capabilities -@jd:body - -
The Android platform offers built-in encoding/decoding for a variety of common media types, -so that you can easily integrate audio, video, and images into your applications. Accessing the platform's media -capabilities is fairly straightforward &mdash you do so using the same intents and -activities mechanism that the rest of Android uses.
- -Android lets you play audio and video from several types of data sources. You can play audio or video from media files stored in the application's resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection. To play audio or video from your application, use the {@link android.media.MediaPlayer} class.
- -The platform also lets you record audio, where supported by the mobile device hardware. Recording of video is not currently supported, but is planned for a future release. To record audio, use the -{@link android.media.MediaRecorder} class. Note that the emulator doesn't have hardware to capture audio, but actual mobile devices are likely to provide these capabilities that you can access through MediaRecorder.
- -For a list of the media formats for which Android offers built-in support, see the Android Media Formats appendix.
- -Media can be played from anywhere: from a raw resource, from a file from the system, -or from an available network (URL).
- -You can play back the audio data only to the standard -output device; currently, that is the mobile device speaker or Bluetooth headset. You -cannot play sound files in the conversation audio.
- -Perhaps the most common thing to want to do is play back media (notably sound) -within your own applications. Doing this is easy:
-res/raw
- folder of your project, where the Eclipse plugin (or aapt) will find it and
- make it into a resource that can be referenced from your R classMediaPlayer, referencing that resource using
- {@link android.media.MediaPlayer#create MediaPlayer.create}, and then call
- {@link android.media.MediaPlayer#start() start()} on the instance:- MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); - mp.start(); --
To stop playback, call {@link android.media.MediaPlayer#stop() stop()}. If
-you wish to later replay the media, then you must
-{@link android.media.MediaPlayer#reset() reset()} and
-{@link android.media.MediaPlayer#prepare() prepare()} the MediaPlayer object
-before calling {@link android.media.MediaPlayer#start() start()} again.
-(create() calls prepare() the first time.)
To pause playback, call {@link android.media.MediaPlayer#pause() pause()}. -Resume playback from where you paused with -{@link android.media.MediaPlayer#start() start()}.
- -You can play back media files from the filesystem or a web URL:
-MediaPlayer using new- MediaPlayer mp = new MediaPlayer(); - mp.setDataSource(PATH_TO_FILE); - mp.prepare(); - mp.start(); --
{@link android.media.MediaPlayer#stop() stop()} and -{@link android.media.MediaPlayer#pause() pause()} work the same as discussed -above.
-Note: It is possible that mp could be
- null, so good code should null check after the new.
- Also, IllegalArgumentException and IOException either
- need to be caught or passed on when using setDataSource(), since
- the file you are referencing may not exist.
Note: -If you're passing a URL to an online media file, the file must be capable of -progressive download.
- -Recording media is a little more involved than playing it back, as you would -probably expect, but it is still fairly simple. There is just a little more set -up to do
-newTITLE, TIMESTAMP, and the all important
- MIME_TYPEMediaRecorder.AudioSource.MICHere is a code example that will hopefully help fill in the gaps:
-Start Recording
-
- recorder = new MediaRecorder();
- ContentValues values = new ContentValues(3);
-
- values.put(MediaStore.MediaColumns.TITLE, SOME_NAME_HERE);
- values.put(MediaStore.MediaColumns.TIMESTAMP, System.currentTimeMillis());
- values.put(MediaStore.MediaColumns.MIME_TYPE, recorder.getMimeContentType());
-
- ContentResolver contentResolver = new ContentResolver();
-
- Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
- Uri newUri = contentResolver.insert(base, values);
-
- if (newUri == null) {
- // need to handle exception here - we were not able to create a new
- // content entry
- }
-
- String path = contentResolver.getDataFilePath(newUri);
-
- // could use setPreviewDisplay() to display a preview to suitable View here
-
- recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
- recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
- recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
- recorder.setOutputFile(path);
-
- recorder.prepare();
- recorder.start();
-
-Stop Recording
-- recorder.stop(); - recorder.release(); -- diff --git a/docs/html/guide/topics/processes/process-lifecycle.jd b/docs/html/guide/topics/processes/process-lifecycle.jd deleted file mode 100644 index 0380f94..0000000 --- a/docs/html/guide/topics/processes/process-lifecycle.jd +++ /dev/null @@ -1,120 +0,0 @@ -page.title=Processes and Application Life Cycle -@jd:body - -
In most cases, every Android application runs in its own Linux process. -This process is created for the application when some of its code needs to -be run, and will remain running until it is no longer needed and -the system needs to reclaim its memory for use by other applications.
- -An unusual and fundamental feature of Android is that an application process's -lifetime is not directly controlled by the application itself. -Instead, it is determined by the system through a combination of the parts of the application -that the system knows are running, how important these things are to the user, -and how much overall memory is available in the system.
- -It is important that -application developers understand how different application components -(in particular {@link android.app.Activity}, {@link android.app.Service}, -and {@link android.content.BroadcastReceiver}) impact the lifetime -of the application's process. Not using these components correctly can -result in the system killing the application's process while it is doing -important work.
- -A common example of a process life-cycle bug is a -{@link android.content.BroadcastReceiver} that starts a thread when it -receives an Intent in its {@link android.content.BroadcastReceiver#onReceive -BroadcastReceiver.onReceive()} -method, and then returns from the function. Once it returns, the system -considers the BroadcastReceiver to be no longer active, and thus, its hosting -process no longer needed (unless other application components are active in -it). So, the system may kill the process at any time to reclaim memory, and in doing so, -it terminates the spawned thread running in the process. The solution to this problem -is to start a {@link android.app.Service} from the BroadcastReceiver, so the -system knows that there is still active work being done in the process.
- -To determine which processes should be killed when low on memory, Android -places each process into an "importance hierarchy" based on the components running in -them and the state of those components. These process types are (in order of importance):
- -There will only ever be a few such processes in the system, and these will only -be killed as a last resort if memory is so low that not even these processes -can continue to run. Generally, at this point, the device has -reached a memory paging state, so this action is required in order to keep the user -interface responsive.
- - -When deciding how to classify a process, the system will base its decision on the most -important level found among all the components currently active in the process. -See the {@link android.app.Activity}, {@link android.app.Service}, and -{@link android.content.BroadcastReceiver} documentation for more detail on how -each of these components contribute to the overall life-cycle of a process. -The documentation for each of these classes describes in more detail how -they impact the overall life-cycle of their application.
- -A process's priority may also be increased based on other dependencies -a process has to it. For example, if process A has bound to a -{@link android.app.Service} with -the {@link android.content.Context#BIND_AUTO_CREATE Context.BIND_AUTO_CREATE} -flag or is using a -{@link android.content.ContentProvider} in process B, then process B's -classification will always be at least as important as process A's.
diff --git a/docs/html/guide/topics/providers/content-providers.jd b/docs/html/guide/topics/providers/content-providers.jd deleted file mode 100644 index 86dcebf..0000000 --- a/docs/html/guide/topics/providers/content-providers.jd +++ /dev/null @@ -1,922 +0,0 @@ -page.title=Content Providers -@jd:body - --Content providers store and retrieve data and make it accessible to all -applications. They're the only way to share data across applications; there's -no common storage area that all Android packages can access. -
- --Android ships with a number of content providers for common data types -(audio, video, images, personal contact information, and so on). You can -see some of them listed in the {@link android.provider android.provider} -package. You can query these providers for the data they contain (although, -for some, you must acquire the proper permission to read the data). -
- --If you want to make your own data public, you have two options: You can -create your own content provider (a {@link android.content.ContentProvider} -subclass) or you can add the data to an existing provider — if there's -one that controls the same type of data and you have permission to write to it. -
- --This document is an introduction to using content providers. After a -brief discussion of the fundamentals, it explores how to query a content -provider, how to modify data controlled by a provider, and how to create -a content provider of your own. -
- - --How a content provider actually stores its data under the covers is -up to its designer. But all content providers implement a common interface -for querying the provider and returning results — as well as for -adding, altering, and deleting data. -
- -
-It's an interface that clients use indirectly, most generally through
-{@link android.content.ContentResolver} objects. You get a ContentResolver
-by calling {@link android.content.Context#getContentResolver
-getContentResolver()} from within the implementation of an Activity
-or other application component:
-
ContentResolver cr = getContentResolver();- -
-You can then use the ContentResolver's methods to interact with whatever -content providers you're interested in. -
- --When a query is initiated, the Android system identifies the content provider -that's the target of the query and makes sure that it is up and running. -The system instantiates all ContentProvider objects; you never need to do it -on your own. In fact, you never deal directly with ContentProvider objects -at all. Typically, there's just a single instance of each type of -ContentProvider. But it can communicate with multiple ContentResolver objects -in different applications and processes. The interaction between processes is -handled by the ContentResolver and ContentProvider classes. -
- - --Content providers expose their data as a simple table on a database model, -where each row is a record and each column is data of a particular type -and meaning. For example, information about people and their phone numbers -might be exposed as follows: -
- -| _ID | -NUMBER | -NUMBER_KEY | -LABEL | -NAME | -TYPE | -
|---|---|---|---|---|---|
| 13 | -(425) 555 6677 | -425 555 6677 | -Kirkland office | -Bully Pulpit | -{@code TYPE_WORK} | -
| 44 | -(212) 555-1234 | -212 555 1234 | -NY apartment | -Alan Vain | -{@code TYPE_HOME} | -
| 45 | -(212) 555-6657 | -212 555 6657 | -Downtown office | -Alan Vain | -{@code TYPE_MOBILE} | -
| 53 | -201.555.4433 | -201 555 4433 | -Love Nest | -Rex Cars | -{@code TYPE_HOME} | -
-Every record includes a numeric {@code _ID} field that uniquely identifies -the record within the table. IDs can be used to match records in related -tables — for example, to find a person's phone number in one table -and pictures of that person in another. -
- --A query returns a {@link android.database.Cursor} object that can move from -record to record and column to column to read the contents of each field. -It has specialized methods for reading each type of data. So, to read a field, -you must know what type of data the field contains. (There's more on query -results and Cursor objects later.) -
- - --Each content provider exposes a public URI (wrapped as a {@link android.net.Uri} -object) that uniquely identifies its data set. A content provider that controls -multiple data sets (multiple tables) exposes a separate URI for each one. All -URIs for providers begin with the string "{@code content://}". The {@code content:} -scheme identifies the data as being controlled by a content provider. -
- --If you're defining a content provider, it's a good idea to also define a -constant for its URI, to simplify client code and make future updates cleaner. -Android defines {@code CONTENT_URI} constants for all the providers that come -with the platform. For example, the URI for the table that matches -phone numbers to people and the URI for the table that holds pictures of -people (both controlled by the Contacts content provider) are: -
- --
{@code android.provider.Contacts.Phones.CONTENT_URI}
-
{@code android.provider.Contacts.Photos.CONTENT_URI}
-
-Similarly, the URIs for the table of recent phone calls and the table -of calendar entries are: -
- --
{@code android.provider.CallLog.Calls.CONTENT_URI}
-
{@code android.provider.Calendar.CONTENT_URI}
-
-The URI constant is used in all interactions with the content provider. -Every {@link android.content.ContentResolver} method takes the URI -as its first argument. It's what identifies which provider the ContentResolver -should talk to and which table of the provider is being targeted. -
- - --You need three pieces of information to query a content provider: -
- --If you're querying a particular record, you also need the ID for that record. -
- - -
-To query a content provider, you can use either the
-{@link android.content.ContentResolver#query ContentResolver.query()}
-method or the {@link android.app.Activity#managedQuery
-Activity.managedQuery()} method.
-Both methods take the same set of arguments, and both return a
-Cursor object. However, {@code managedQuery()}
-causes the activity to manage the life cycle of the Cursor. A managed Cursor
-handles all of the niceties, such as unloading itself when the activity pauses,
-and requerying itself when the activity restarts. You can ask an Activity to
-begin managing an unmanaged Cursor object for you by calling
-{@link android.app.Activity#startManagingCursor
-Activity.startManagingCursor()}.
-
-The first argument to either {@link android.content.ContentResolver#query query()}
-or {@link android.app.Activity#managedQuery managedQuery()} is the provider URI
-— the {@code CONTENT_URI} constant that identifies a particular
-ContentProvider and data set (see URIs earlier).
-
-To restrict a query to just one record, you can append the {@code _ID} value for -that record to the URI — that is, place a string matching the ID as the -last segment of the path part of the URI. For example, if the ID is 23, -the URI would be: -
- -{@code content://. . . ./23}
- -
-There are some helper methods, particularly
-{@link android.content.ContentUris#withAppendedId
-ContentUris.withAppendedId()} and {@link
-android.net.Uri#withAppendedPath Uri.withAppendedPath()},
-that make it easy to append an ID to a URI. Both are static methods that return
-a Uri object with the ID added. So, for example, if you were looking for record
-23 in the database of people contacts, you might construct a query as follows:
-
-import android.provider.Contacts.People; -import android.content.ContentUris; -import android.net.Uri; -import android.database.Cursor; - -// Use the ContentUris method to produce the base URI for the contact with _ID == 23. -Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23); - -// Alternatively, use the Uri method to produce the base URI. -// It takes a string rather than an integer. -Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23"); - -// Then query for this specific record: -Cursor cur = managedQuery(myPerson, null, null, null, null); -- -
-The other arguments to the {@link android.content.ContentResolver#query query()}
-and {@link android.app.Activity#managedQuery managedQuery()} methods delimit
-the query in more detail. They are:
-
A filter detailing which rows to return, formatted as an SQL {@code WHERE} -clause (excluding the {@code WHERE} itself). A {@code null} value returns -all rows (unless the URI limits the query to a single record).
Selection arguments.
A sorting order for the rows that are returned, formatted as an SQL -{@code ORDER BY} clause (excluding the {@code ORDER BY} itself). A {@code null} -value returns the records in the default order for the table, which may be -unordered.
-Let's look at an example query to retrieve a list of contact names and their -primary phone numbers: -
- -
-import android.provider.Contacts.People;
-import android.database.Cursor;
-
-// Form an array specifying which columns to return.
-String[] projection = new String[] {
- People._ID,
- People._COUNT,
- People.NAME,
- People.NUMBER
- };
-
-// Get the base URI for the People table in the Contacts content provider.
-Uri contacts = People.CONTENT_URI;
-
-// Make the query.
-Cursor managedCursor = managedQuery(contacts,
- projection, // Which columns to return
- null, // Which rows to return (all rows)
- null, // Selection arguments (none)
- // Put the results in ascending order by name
- People.NAME + " ASC");
-
-
--This query retrieves data from the People table of the Contacts content -provider. It gets the name, primary phone number, and unique record ID for -each contact. It also reports the number of records that are returned as -the {@code _COUNT} field of each record. -
- --The constants for the names of the columns are defined in various interfaces -— {@code _ID} and {@code _COUNT} in -{@link android.provider.BaseColumns BaseColumns}, {@code NAME} in {@link android.provider.Contacts.PeopleColumns PeopleColumns}, and {@code NUMBER} -in {@link android.provider.Contacts.PhonesColumns PhoneColumns}. The -{@link android.provider.Contacts.People Contacts.People} class implements -each of these interfaces, which is why the code example above could refer -to them using just the class name. -
- - --A query returns a set of zero or more database records. The names of the -columns, their default order, and their data types are specific to each -content provider. -But every provider has an {@code _ID} column, which holds a unique numeric -ID for each record. Every provider can also report the number -of records returned as the {@code _COUNT} column; its value -is the same for all rows. -
- --Here is an example result set for the query in the previous section: -
- -| _ID | -_COUNT | -NAME | -NUMBER | -
|---|---|---|---|
| 44 | -3 | -Alan Vain | -212 555 1234 | -
| 13 | -3 | -Bully Pulpit | -425 555 6677 | -
| 53 | -3 | -Rex Cars | -201 555 4433 | -
-The retrieved data is exposed by a {@link android.database.Cursor Cursor} -object that can be used to iterate backward or forward through the result -set. You can use this object only to read the data. To add, modify, or -delete data, you must use a ContentResolver object. -
- - -
-The Cursor object returned by a query provides access to a recordset of
-results. If you have queried for a specific record by ID, this set will
-contain only one value. Otherwise, it can contain multiple values.
-(If there are no matches, it can also be empty.) You
-can read data from specific fields in the record, but you must know the
-data type of the field, because the Cursor object has a separate method
-for reading each type of data — such as {@link
-android.database.Cursor#getString getString()}, {@link
-android.database.Cursor#getInt getInt()}, and {@link
-android.database.Cursor#getFloat getFloat()}.
-(However, for most types, if you call the method for reading strings,
-the Cursor object will give you the String representation of the data.)
-The Cursor lets you request the column name from the index of the column,
-or the index number from the column name.
-
-The following snippet demonstrates reading names and phone numbers from -the query illustrated earlier: -
- -
-import android.provider.Contacts.People;
-
-private void getColumnData(Cursor cur){
- if (cur.moveToFirst()) {
-
- String name;
- String phoneNumber;
- int nameColumn = cur.getColumnIndex(People.NAME);
- int phoneColumn = cur.getColumnIndex(People.NUMBER);
- String imagePath;
-
- do {
- // Get the field values
- name = cur.getString(nameColumn);
- phoneNumber = cur.getString(phoneColumn);
-
- // Do something with the values.
- ...
-
- } while (cur.moveToNext());
-
- }
-}
-
-
-
-If a query can return binary data, such as an image or sound, the data
-may be directly entered in the table or the table entry for that data may be
-a string specifying a {@code content:} URI that you can use to get the data.
-In general, smaller amounts of data (say, from 20 to 50K or less) are most often
-directly entered in the table and can be read by calling
-{@link android.database.Cursor#getBlob Cursor.getBlob()}.
-It returns a byte array.
-
-If the table entry is a {@code content:} URI, you should never try to open
-and read the file directly (for one thing, permissions problems can make this
-fail). Instead, you should call
-{@link android.content.ContentResolver#openInputStream
-ContentResolver.openInputStream()} to get an
-{@link java.io.InputStream} object that you can use to read the data.
-
-Data kept by a content provider can be modified by: -
- --All data modification is accomplished using {@link android.content.ContentResolver} -methods. Some content providers require a more restrictive permission for writing -data than they do for reading it. If you don't have permission to write to a -content provider, the ContentResolver methods will fail. -
- - -
-To add a new record to a content provider, first set up a map of key-value pairs
-in a {@link android.content.ContentValues} object, where each key matches
-the name of a column in the content provider and the value is the desired
-value for the new record in that column. Then call {@link
-android.content.ContentResolver#insert ContentResolver.insert()} and pass
-it the URI of the provider and the ContentValues map. This method returns
-the full URI of the new record — that is, the provider's URI with
-the appended ID for the new record. You can then use this URI to query and
-get a Cursor over the new record, and to further modify the record.
-Here's an example:
-
-import android.provider.Contacts.People; -import android.content.ContentResolver; -import android.content.ContentValues; - -ContentValues values = new ContentValues(); - -// Add Abraham Lincoln to contacts and make him a favorite. -values.put(People.NAME, "Abraham Lincoln"); -// 1 = the new contact is added to favorites -// 0 = the new contact is not added to favorites -values.put(People.STARRED, 1); - -Uri uri = getContentResolver().insert(People.CONTENT_URI, values); -- - -
-Once a record exists, you can add new information to it or modify -existing information. For example, the next step in the example above would -be to add contact information — like a phone number or an IM or e-mail -address — to the new entry. -
- --The best way to add to a record in the Contacts database is to append -the name of the table where the new data goes to the URI for the -record, then use the amended URI to add the new data values. Each -Contacts table exposes a name for this purpose as a {@code -CONTENT_DIRECTORY} constant. The following code continues the previous -example by adding a phone number and e-mail address for the record -just created: -
- --Uri phoneUri = null; -Uri emailUri = null; - -// Add a phone number for Abraham Lincoln. Begin with the URI for -// the new record just returned by insert(); it ends with the _ID -// of the new record, so we don't have to add the ID ourselves. -// Then append the designation for the phone table to this URI, -// and use the resulting URI to insert the phone number. -phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); - -values.clear(); -values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE); -values.put(People.Phones.NUMBER, "1233214567"); -getContentResolver().insert(phoneUri, values); - -// Now add an email address in the same way. -emailUri = Uri.withAppendedPath(uri, People.ContactMethods.CONTENT_DIRECTORY); - -values.clear(); -// ContactMethods.KIND is used to distinguish different kinds of -// contact methods, such as email, IM, etc. -values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL); -values.put(People.ContactMethods.DATA, "test@example.com"); -values.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_HOME); -getContentResolver().insert(emailUri, values); -- -
-You can place small amounts of binary data into a table by calling
-the version of {@link android.content.ContentValues#put
-ContentValues.put()} that takes a byte array.
-That would work for a small icon-like image or a short audio clip, for example.
-However, if you have a large amount of binary data to add, such as a photograph
-or a complete song, put a {@code content:} URI for the data in the table and call
-{@link android.content.ContentResolver#openOutputStream
-ContentResolver.openOutputStream()}
-with the file's URI. (That causes the content provider to store the data
-in a file and record the file path in a hidden field of the record.)
-
-In this regard, the {@link android.provider.MediaStore} content -provider, the main provider that dispenses image, audio, and video -data, employs a special convention: The same URI that is used with -{@code query()} or {@code managedQuery()} to get meta-information -about the binary data (such as, the caption of a photograph or the -date it was taken) is used with {@code openInputStream()} -to get the data itself. Similarly, the same URI that is used with -{@code insert()} to put meta-information into a MediaStore record -is used with {@code openOutputStream()} to place the binary data there. -The following code snippet illustrates this convention: -
- -
-import android.provider.MediaStore.Images.Media;
-import android.content.ContentValues;
-import java.io.OutputStream;
-
-// Save the name and description of an image in a ContentValues map.
-ContentValues values = new ContentValues(3);
-values.put(Media.DISPLAY_NAME, "road_trip_1");
-values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles");
-values.put(Media.MIME_TYPE, "image/jpeg");
-
-// Add a new record without the bitmap, but with the values just set.
-// insert() returns the URI of the new record.
-Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
-
-// Now get a handle to the file for that record, and save the data into it.
-// Here, sourceBitmap is a Bitmap object representing the file to save to the database.
-try {
- OutputStream outStream = getContentResolver().openOutputStream(uri);
- sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
- outStream.close();
-} catch (Exception e) {
- Log.e(TAG, "exception while writing image", e);
-}
-
-
-
-
-To batch update a group of records (for example, to change "NY" to "New York"
-in all fields), call the {@link
-android.content.ContentResolver#update ContentResolver.update()}
-method with the columns and values to change.
-
-To delete a single record, call {{@link
-android.content.ContentResolver#delete ContentResolver.delete()}
-with the URI of a specific row.
-
-To delete multiple rows, call {@link
-android.content.ContentResolver#delete ContentResolver.delete()}
-with the URI of the type of record to delete (for example, {@code android.provider.Contacts.People.CONTENT_URI}) and an SQL {@code WHERE}
-clause defining which rows to delete. (Caution:
-Be sure to include a valid {@code WHERE} clause if you're deleting a general
-type, or you risk deleting more records than you intended!).
-
-To create a content provider, you must: -
- -Extend the {@link android.content.ContentProvider} class to provide -access to the data.
Declare the content provider in the manifest file for your -application (AndroidManifest.xml).
-The following sections have notes on the last two of these tasks. -
- - --You define a {@link android.content.ContentProvider} subclass to -expose your data to others using the conventions expected by -ContentResolver and Cursor objects. Principally, this means -implementing six abstract methods declared in the ContentProvider class: -
- -{@code query()}
-
{@code insert()}
-
{@code update()}
-
{@code delete()}
-
{@code getType()}
-
{@code onCreate()}
-The {@code query()} method must return a {@link android.database.Cursor} object -that can iterate over the requested data. Cursor itself is an interface, but -Android provides some ready-made Cursor objects that you can use. For example, -{@link android.database.sqlite.SQLiteCursor} can iterate over data stored in -an SQLite database. You get the Cursor object by calling any of the {@link -android.database.sqlite.SQLiteDatabase SQLiteDatabase} class's {@code query()} -methods. There are other Cursor implementations — such as {@link -android.database.MatrixCursor} — for data not stored in a database. -
- --Because these ContentProvider methods can be called from -various ContentResolver objects in different processes and threads, -they must be implemented in a thread-safe manner. -
- -
-As a courtesy, you might also want to call {@link android.content.ContentResolver#notifyChange(android.net.Uri,android.database.ContentObserver)
-ContentResolver.notifyChange()} to notify listeners when there are
-modifications to the data.
-
-Beyond defining the subclass itself, there are other steps you should take -to simplify the work of clients and make the class more accessible: -
- -public static final Uri CONTENT_URI =
- Uri.parse("content://com.example.codelab.transporationprovider");
-
--If the provider has subtables, also define {@code CONTENT_URI} constants for -each of the subtables. These URIs should all have the same authority (since -that identifies the content provider), and be distinguished only by their paths. -For example: -
- -{@code content://com.example.codelab.transporationprovider/train}
-
{@code content://com.example.codelab.transporationprovider/air/domestic}
-
{@code content://com.example.codelab.transporationprovider/air/international}
-For an overview of {@code content:} URIs, see the Content URI -Summary at the end of this document. -
Define the column names that the content provider will return to clients. -If you are using an underlying database, these column names are typically -identical to the SQL database column names they represent. Also define -{@code public static} String constants that clients can use to specify -the columns in queries and other instructions. -
- --Be sure to include an integer column named "{@code _id}" -(with the constant {@code _ID}) for -the IDs of the records. You should have this field whether or not you have -another field (such as a URL) that is also unique among all records. If -you're using the SQLite database, the {@code _ID} field should be the -following type: -
- -{@code INTEGER PRIMARY KEY AUTOINCREMENT}
- --The {@code AUTOINCREMENT} descriptor is optional. But without it, SQLite -increments an ID counter field to the next number above the largest -existing number in the column. If you delete the last row, the next row added -will have the same ID as the deleted row. {@code AUTOINCREMENT} avoids this -by having SQLite increment to the next largest value whether deleted or not. -
-Carefully document the data type of each column. Clients need this -information to read the data.
If you are handling a new data type, you must define a new MIME type
-to return in your implementation of {@link
-android.content.ContentProvider#getType ContentProvider.getType()}.
-The type depends in part on whether or not the {@code content:} URI submitted
-to {@code getType()} limits the request to a specific record. There's one
-form of the MIME type for a single record and another for multiple records.
-Use the {@link android.net.Uri Uri} methods to help determine what is being
-requested. Here is the general format for each type:
For a single record: {@code vnd.android.cursor.item/vnd.yourcompanyname.contenttype - -
For example, a request for train record 122, like this URI,
-{@code content://com.example.transportationprovider/trains/122}
- -might return this MIME type:
-{@code vnd.android.cursor.item/vnd.example.rail}
-For multiple records: {@code vnd.android.cursor.dir/vnd.yourcompanyname.contenttype}
- -For example, a request for all train records, like the following URI,
-{@code content://com.example.transportationprovider/trains}
- -might return this MIME type:
-{@code vnd.android.cursor.dir/vnd.example.rail}
-If you are exposing byte data that's too big to put in the table itself
-— such as a large bitmap file — the field that exposes the
-data to clients should actually contain a {@code content:} URI string.
-This is the field that gives clients access to the data file. The record
-should also have another field, named "{@code _data}" that lists the exact file
-path on the device for that file. This field is not intended to be read by
-the client, but by the ContentResolver. The client will call {@link
-android.content.ContentResolver#openInputStream ContentResolver.openInputStream()}
-on the user-facing field holding the URI for the item. The ContentResolver
-will request the "{@code _data}" field for that record, and because
-it has higher permissions than a client, it should be able to access
-that file directly and return a read wrapper for the file to the client.
-For an example of a private content provider implementation, see the -NodePadProvider class in the Notepad sample application that ships with the SDK. -
- - --To let the Android system know about the content provider you've developed, -declare it with a {@code <provider>} element in the application's -AndroidManifest.xml file. Content providers that are not declared in the -manifest are not visible to the Android system -
- --The {@code name} attribute is the fully qualified name of the ContentProvider -subclass. The {@code authorities} attribute is the authority part of the -{@code content:} URI that identifies the provider. -For example if the ContentProvider subclass is AutoInfoProvider, the -{@code <provider>} element might look like this: -
- --<provider name="com.example.autos.AutoInfoProvider" - authorities="com.example.autos.autoinfoprovider" - . . . /> -</provider> -- -
-Note that the {@code authorities} attribute omits the path part of a -{@code content:} URI. For example, if AutoInfoProvider controlled subtables -for different types of autos or different manufacturers, -
- -{@code content://com.example.autos.autoinfoprovider/honda}
-
{@code content://com.example.autos.autoinfoprovider/gm/compact}
-
{@code content://com.example.autos.autoinfoprovider/gm/suv}
-those paths would not be declared in the manifest. The authority is what -identifies the provider, not the path; your provider can interpret the path -part of the URI in any way you choose. -
- --Other {@code <provider>} attributes can set permissions to read and -write data, provide for an icon and text that can be displayed to users, -enable and disable the provider, and so on. Set the {@code multiprocess} -attribute to "{@code true}" if data does not need to be synchronized between -multiple running versions of the content provider. This permits an instance -of the provider to be created in each client process, eliminating the need -to perform IPC. -
- - --Here is a recap of the important parts of a content URI: -
- -
-
-
The authority part of the URI; it identifies the content provider. -For third-party applications, this should be a fully-qualified class name -(reduced to lowercase) to ensure uniqueness. The authority is declared in -the {@code <provider>} element's {@code authorities} attribute:
- -<provider name=".TransportationProvider" - authorities="com.example.transportationprovider" - . . . >
The path that the content provider uses to determine what kind of data is -being requested. This can be zero or more segments long. If the content provider -exposes only one type of data (only trains, for example), it can be absent. -If the provider exposes several types, including subtypes, it can be several -segments long — for example, "{@code land/bus}", "{@code land/train}", -"{@code sea/ship}", and "{@code sea/submarine}" to give four possibilities.
The ID of the specific record being requested, if any. This is the -{@code _ID} value of the requested record. If the request is not limited to -a single record, this segment and the trailing slash are omitted:
- -{@code content://com.example.transportationprovider/trains}
-This page describes the different types of resources that you can -externalize from your code and package with your application.
- - -For more details on how to use resources in your application, please see the - Resources and Internationalization - documentation.
- - -All simple resource values can be expressed as a string, using various -formats to unambiguously indicate the type of resource being created. For -this reason, these values can be defined both as standard resources -(under res/values/), as well as direct values supplied for -mappings in styles and themes, and attributes in -XML files such as layouts.
- - - -- A color value specifies an RGB value with an alpha channel, which can - be used in various places such as specifying a solid color for a {@link android.graphics.drawable.Drawable} - or the color to use for text. A color value always begins with - a pound (#) character and then followed by the Alpha-Red-Green-Blue information - in one of the following formats: -
-- If you want to retrieve the color represented by a resource ID, you can call - the {@link android.content.res.Resources#getColor(int) Resources.getColor()} method. -
-
- Source file format: XML file requiring a
- <?xml version="1.0" encoding="utf-8"?> declaration, and
- a root <resources> element containing one or more
- <color> tags.
-
- Resource source file location: res/values/colors.xml (file name is arbitrary) -
-- Compiled resource datatype: Resource pointer to a Java int. -
-- Resource reference name: -
-R.color.some_name
- @[package:]color/some_name (where some_name is the name of a specific color)
- - Syntax -
--<color name=color_name>#color_value</color> --
- Example XML Declaration -
-- The following code declares two colors, the first fully opaque, and the - second translucent. -
--<resources> - <color name="opaque_red">#f00</color> - <color name="translucent_red">#80ff0000</color> -</resources> --
- Example Code Use -
-- Example Java code -
--// Retrieve a color value. -int color = getResources.getColor(R.color.opaque_red); --
- Example XML code -
--<TextView android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:textAlign="center" - android:textColor="@color/translucent_red" - android:text="Some Text"/> -- - - -
- Strings, with optional simple formatting, can be
-stored and retrieved as resources. You can add formatting to your string by
-using three standard HTML tags: <b>, <i>, and <u>. To
-guarantee getting an unstyled string only (the raw text) call the
-toString() method of the retrieved CharSequence object.
-Methods that accept string resources should be able to process these styling
-tags.
-
- If you want to retrieve the String represented by a resource ID, you can call the {@link android.content.Context#getString(int) Context.getString()} method. -
-- Note: If you use an apostrophe or a quote in your string, you must either escape it or enclose the whole string in the other kind of enclosing quotes: -
--<string name="good_example">"This'll work"</string> -<string name="good_example_2">This\'ll also work</string> -<string name="bad_example">This won't work!</string> -<string name="bad_example_2">XML encodings won't work either!</string> --
- Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?> declaration, and a root <resources> element containing one or more <string> tags.
-
- Resource source file location: res/values/strings.xml (file name is arbitrary) -
-- Compiled resource datatype: Resource pointer to a Java CharSequence. -
-- Resource reference name: -
-R.string.some_name
- @[package:]string/some_name (where some_name is the name of a specific string)
- - Syntax -
--<string name=string_name>string_value</string> --
- Example XML Declaration -
-- The following declares two strings: the first — simple text with no - formatting (resulting in a CharSequence that is simply a String object) — the second includes formatting information in the string (resulting - in a CharSequence that is a complex data structure). If you are using the custom editor for string files in Eclipse, the HTML formatting tags will automatically be escaped and you will need to use {@link android.content.Context#getString(int) Context.getString()} and {@link android.text.Html#fromHtml} to retreive the resource and then convert it to formatted text. -
--<resources> - <string name="simple_welcome_message">Welcome!</string> - <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> -</resources> --
- Example Code Use -
-- Example Java code -
--// Assign a styled string resource to a TextView -// on the current screen. -CharSequence str = getString(R.string.styled_welcome_message); -TextView tv = (TextView)findViewByID(R.id.text); -tv.setText(str); --
- Example XML code -
--<TextView android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:textAlign="center" - android:text="@string/simple_welcome_message"/> -- - -
-Sometimes you may want to create a styled text resource that is also used as a -format string. This cannot be done directly because there is no way of passing -the styled text as the format string argument of String.format() -without stripping out the style information. The workaround is to store the -style tags as escaped HTML tags, and then convert the escaped HTML string into -a styled text after formatting has taken place. -
--To use styled text as a format string, do the following. -
--<resources> - <string name="search_results_resultsTextFormat">%1$d results for <b>&quot;%2$s&quot;</b></string> -</resources> --
-In this example the format string has two arguments: %1$d is a decimal number, %2$s is a string.
-
-String escapedTitle = TextUtil.htmlEncode(title); --
-String resultsTextFormat = getContext().getResources().getString(R.string.search_results_resultsTextFormat); -String resultsText = String.format(resultsTextFormat, count, escapedTitle); -CharSequence styledResults = Html.fromHtml(resultsText); --
You can create common dimensions to use for various screen elements by -defining dimension values in XML. A dimension resource is a number followed by -a unit of measurement. For example: 10px, 2in, 5sp. Here are the units of -measurement supported by Android:
-Dimension values are not normally used as raw resources, but rather as -attribute values in XML files. You can, however, create plain resources -containing this data type.
- -Source file format: XML file requiring a <?xml
-version="1.0" encoding="utf-8"?> declaration, and a root
-<resources> element containing one or more
-<dimen> tags.
Resource source file location: res/values/dimens.xml (File -name is arbitrary; standard practice is to put all dimensions in one file -devoted to dimensions.)
-Compiled resource datatype: Resource pointer to a -dimension.
-- Resource reference name: -
-R.dimen.some_name
- @[package:]dimen/some_name (where some_name is the name of a specific <dimen> element)
- - Syntax -
--<dimen name=dimen_name>dimen_value</dimen> --
- Example XML Declaration -
-- The following code declares several dimension values. -
--<resources> - <dimen name="one_pixel">1px</dimen> - <dimen name="double_density">2dp</dimen> - <dimen name="sixteen_sp">16sp</dimen> -</resources> --
- Example Code Use -
-- Example Java code: -
--float dimen = Resources.getDimen(R.dimen.one_pixel); --
- Example XML code: -
--<TextView android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:textSize="@dimen/sixteen_sp"/> -- - -
A {@link android.graphics.drawable.Drawable} is a type of resource that -you retrieve with {@link android.content.res.Resources#getDrawable -Resources.getDrawable()} and use to draw to the screen. There are a -number of drawable resources that can be created.
- - - -Android supports bitmap resource files in a few different formats: png -(preferred), jpg (acceptable), gif (discouraged). The bitmap file itself is -compiled and referenced by the file name without the extension (so -res/drawable/my_picture.png would be referenced as R.drawable.my_picture).
- -- Source file formats: png (preferred), jpg (acceptable), gif (discouraged). One resource per file. -
-- Resource file location: res/drawable/some_file.png or some_file.jpg or some_file.gif. -
-- Compiled resource datatype: Resource pointer to a {@link android.graphics.drawable.BitmapDrawable BitmapDrawable}. -
-- Resource reference name: -
-R.drawable.some_file
- @[package:]drawable/some_file
- For more discussion and examples using drawable resources, see the discussion in 2D Graphics.
- - -You can create a {@link android.graphics.drawable.PaintDrawable} object that is a rectangle of color, -with optionally rounded corners. This element can be defined in any of the -files inside res/values/.
-Source file format: XML file requiring a <?xml
-version="1.0" encoding="utf-8"?> declaration, and a root
-<resources> element containing one or more
-<drawable> tags.
- Resource source file location: res/values/colors.xml (File name is arbitrary; standard practice is to put the PaintDrawable items in the file along with the numeric color values.) -
-- Compiled resource datatype: Resource pointer to a {@link android.graphics.drawable.PaintDrawable}. -
-- Resource reference name: -
-R.drawable.some_name
- @[package:]drawable/some_name (where some_name is the name of a specific resource)
- - Syntax -
--<drawable name=color_name>color_value</drawable> --
- Example XML Declaration -
-- The following code declares several color drawables. -
--<resources> - <drawable name="solid_red">#f00</drawable> - <drawable name="solid_blue">#0000ff</drawable> - <drawable name="solid_green">#f0f0</drawable> -</resources> --
- Example Code Use -
-- Example Java code -
--// Assign a PaintDrawable as the background to -// a TextView on the current screen. -Drawable redDrawable = Resources.getDrawable(R.drawable.solid_red); -TextView tv = (TextView)findViewByID(R.id.text); -tv.setBackground(redDrawable); --
- Example XML code -
--<TextView android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:textAlign="center" - android:background="@drawable/solid_red"/> -- - -
- Android supports a stretchable bitmap image, called a - {@link android.graphics.NinePatch} graphic. This is a PNG image in which - you define stretchable sections that Android will resize to fit the object - at display time to accommodate variable sized sections, such as text strings. - You typically assign this resource to the View's background. An example use - of a stretchable image is the button backgrounds that Android uses; buttons - must stretch to accommodate strings of various lengths. -
- -- Source file format: PNG — one resource per file -
-- Resource source file location: res/drawable/some_name.9.png (must end in .9.png) -
-- Compiled resource datatype: Resource pointer to a {@link android.graphics.drawable.NinePatchDrawable NinePatchDrawable}. -
-- Resource reference name: -
-R.drawable.some_file
- @[package:]drawable.some_file
- For more information and examples using NinePatch drawables, see the discussion -in 2D Graphics.
- - - -- Android can perform simple animation on a graphic, or a series of graphics. These include rotations, fading, moving, and stretching. -
-
- Source file format: XML file, one resource per file, one root tag with no <?xml> declaration
-
- Resource file location: res/anim/some_file.xml -
-- Compiled resource datatype: Resource pointer to an {@link android.view.animation.Animation}. -
-- Resource reference name: -
-R.anim.some_file
- @[package:]anim/some_file
- - Syntax -
-
- The file must have a single root element: this will be either a single <alpha>, <scale>, <translate>, <rotate>, interpolator element, or <set> element that holds groups of these elements (which may include another <set>). By default, all elements are applied simultaneously. To have them occur sequentially, you must specify the startOffset attribute.
-
-<set android:shareInterpolator=boolean> // Only required if multiple tags are used. - <alpha android:fromAlpha=float - android:toAlpha=float > | - <scale android:fromXScale=float - android:toXScale=float - android:fromYScale=float - android:toYScale=float - android:pivotX=string - android:pivotY=string > | - <translate android:fromX=string - android:toX=string - android:fromY=string - android:toY=string > | - <rotate android:fromDegrees=float - android:toDegrees=float - android:pivotX=string - android:pivotY=string > | - <interpolator tag> - <set> -</set> --
- Elements and Attributes -
-scale supports the following attributes:
-
-In addition to the attributes defined for each element above, the elements
-<alpha>, <scale>, <translate>,
-<rotate>, and <set> all support the following attributes (inherited
-from the {@link android.view.animation.Animation} class):
-
For more discussion and animation code samples, see the discussion in the -2D Graphics document.
- - - -Application menus (Options Menu, Context Menu, or Sub Menu) can be defined as -XML resources and inflated by your application using {@link android.view.MenuInflater}.
- -Source file format: XML file, one resource per file, one root tag,
-<?xml> declaration not required.
Resource file location: res/menu/some_file.xml
-Compiled resource datatype: Resource pointer to a {@link android.view.Menu} (or subclass) resource.
-Resource reference name:
-R.menu.some_fileThe file must have a single root element: a <menu> element. In all,
-there are three valid elements: <menu>, <group> and <item>. The
-<item> and <group> elements must be the children of a <menu>, but <item>
-elements can also be the children of a <group>, and another <menu> element may be the child
-of an <item> (to create a Sub Menu).
-<menu xmlns:android="http://schemas.android.com/apk/res/android"> - - <item android:id="@+id/example_item - android:title="Example Item" - android:icon="@drawable/example_item_icon" /> - - <group android:id="@+id/example_group"> - <item android:id="@+id/example_item2 - android:title="Example Item 2" - android:icon="@drawable/example_item2_icon" /> - </group> - - <item android:id="@+id/example_submenu - android:title="Example Sub Menu" > - <menu> - <item android:id="@+id/example_submenu_item - android:title="Example Sub Menu Item" /> - </menu> - </item> - -</menu> -- -
All attributes must be defined with the android namespace (e.g., android:icon="@drawable/icon").
-<item> and <group> nodes. No attributes.<item> elements. Valid attributes:
- <menu> element (for a Sub Menu). Valid attributes:
- For more discussion on how to create menus in XML and inflate them in your application, -read Creating Menus.
- - - -Android lets you specify screen layouts using XML elements inside an XML
-file, similar to designing screen layout for a webpage in an HTML file. Each
-file contains a whole screen or a part of a screen, and is compiled into a
-View resource that can be passed in to
-{@link android.app.Activity#setContentView(int) Activity.setContentView} or used as a
-reference by other layout resource elements. Files are saved in the
-res/layout/ folder of your project, and compiled by the Android resource
-compiler, aapt.
Every layout XML file must evaluate to a single root -element. First we'll describe how to use the standard XML tags understood by -Android as it is shipped, and then we'll give a little information on how you -can define your own custom XML elements for custom View objects. - -
The root element must have -the Android namespace "http://schemas.android.com/apk/res/android" defined in -the root element.
- -For a complete discussion on creating layouts, see the -User Interface topic.
- - Source file format: XML file
-requiring a <?xml version="1.0" encoding="utf-8"?>
-declaration, and a root element of one of the supported XML layout elements.
-
Resource file location: -res/layout/some_file.xml.
-- Compiled resource datatype: Resource pointer to a {@link android.view.View} (or subclass) resource. -
-- Resource reference name: -
-R.layout.some_file
- @[package:]layout/some_file
- - Syntax -
--<ViewGroupClass xmlns:android="http://schemas.android.com/apk/res/android" - id="@+id/string_name" (attributes)> - <widget or other nested ViewGroupClass>+ - <requestFocus/>(0 or 1 per layout file, assigned to any element) -</ViewGroupClass> --
The file must have a single root element. This can be a ViewGroup class that contains other elements, or a widget (or custom item) if it's only one object. By default, you can use any (case-sensitive) Android {@link android.widget widget} or {@link android.view.ViewGroup ViewGroup} class name as an element. These elements support attributes that apply to the underlying class, but the naming is not as clear. How to discover what attributes are supported for what tags is discussed below. You should not assume that any nesting is valid (for example you cannot enclose <TextView> elements inside a <ListLayout>).
If a class derives from another class, the XML element inherits all the attributes from the element that it "derives" from. So, for example, <EditText> is the corresponding XML element for the EditText class. It exposes its own unique attributes (EditText_numeric), as well as all attributes supported by <TextView> and <View>. For the id attribute of a tag in XML, you should use a special syntax: "@+id/somestringvalue". The "@+" syntax creates a resource number in the R.id class, if one doesn't exist, or uses it, if it does exist. When declaring an ID value for an XML tag, use this syntax. Example: <TextView id="@+id/nameTextbox"/>, and refer to it this way in Java: findViewById(R.id.nameTextbox). All elements support the following values:
xmlns:android="http://schemas.android.com/apk/res/android" - Required for the root element only.
- - What Attributes Are Supported for What Elements? -
-
- Android uses the {@link android.view.LayoutInflater} class at run time to load an XML layout resource and translate it into visual elements. By default, all widget class names are supported directly as tags, but a full list of supported tags and attributes is listed in the {@link android.R.styleable} reference page. However, the attribute names are somewhat obscure. If an underscore appears in the name, this indicates that it is an attribute — typically of the element before the underscore. So, for example, EditText_autoText means that the <EditText> tag supports an attribute autoText. When you actually use the attribute in that element, use only the portion after the last underscore, and prefix the attribute with the prefix "android:". So, for example, if {@link android.R.styleable} lists the following values:
-
TextView
- TextView_lines
- TextView_maxlines
- - You could create an element like this: -
--<TextView android:lines="10" android:maxlines="20"/> --
- This would create a {@link android.widget.TextView} object and set its lines and maxlines properties. -
-- Attributes come from three sources: -
-TextView supports TextView_text, as discussed above.
- <TextView> element supports all the attributes that the <View> element exposes — a long list, including View_paddingBottom and View_scrollbars. These too are used without the class name: <TextView android:paddingBottom="20" android:scrollbars="horizontal" />.
- android:layout_gravity for an object wrapped by a <LinearLayout> element. Remember that each LayoutParams subclass also supports inherited attributes. Attributes exposed by each subclass are given in the format someLayoutParamsSubclass_Layout_layout_someproperty. This defines an attribute "android:layout_someproperty". Here is an example of how Android documentation lists the properties of the {@link android.widget.LinearLayout.LayoutParams LinearLayout.LayoutParams} class:
- gravity attribute
- height attribute
- weight attribute
- width attribute
- - Here is an example that sets some of these values on a few objects, including direct attributes, inherited attributes, and LayoutParams attributes: -
--<?xml version="1.0" encoding="utf-8"?> -<!-- res/main_screen.xml --> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:orientation="vertical" // The object's own orientation property - android:padding="4" // Inherited View property - android:gravity="center" // The object's own property - android:layout_width="fill_parent" // Parent object's LinearLayout.LayoutParams.width - android:layout_height="fill_parent"> // Parent object's LinearLayout.LayoutParams.height - - <TextView android:layout_width="fill_parent" // TextView.LayoutParams.width - android:layout_height="wrap_content" // TextView.LayoutParams.height - android:layout_weight="0" // TextView.LayoutParams.weight - android:paddingBottom="4" // TextView.paddingBottom - android:text="@string/redirect_getter"/> // TextView.text - - <EditText id="@+id/text" - android:layout_width="fill_parent" // EditText.LayoutParams.width - android:layout_height="wrap_content" // EditText.LayoutParams.height - android:layout_weight="0" // EditText.LinearLayoutParams.weight - android:paddingBottom="4"> // EditText.paddingBottom - <requestFocus /> - </EditText> - - <Button id="@+id/apply" - android:layout_width="wrap_content" // Button.LayoutParams.width - android:layout_height="wrap_content" // Button.LayoutParams.height - android:text="@string/apply" /> // TextView.text -</LinearLayout> --
- Example Code Use -
-- The most common use is to load the XML file (located at res/main_screen.xml) and use it as the current screen, as shown here with the preceding file: -
--setContentView(R.layout.main_screen); --
- However, layout elements can also represent repeating elements used as templates. -
- -Also see User Interface for more information on layouts.
- - - -- You can define custom elements to use in layout resources. These custom elements can then be used the same as any Android layout elements: that is, you can use them and specify their attributes in other resources. The ApiDemos sample application has an example of creating a custom layout XML tag, LabelView. To create a custom element, you will need the following files: -
-<declare-styleable id=your_java_class_name>. See res/layout/attrs.xml in ApiDemos.
-
- Source file format: XML file without an <?xml> declaration, and a <resources> root element containing one or more custom element tags.
-
- Resource file location: res/values/attrs.xml (file name is arbitrary). -
-- Compiled resource datatype: Resource pointer to a {@link android.view.View} (or subclass) resource. -
-- Resource reference name: R.styleable.some_file (Java). -
- - - -- A style is one or more attributes applied to a single element (for example, 10 point red Arial font, applied to a TextView). A style is applied as an attribute to an element in a layout XML file. -
-- A theme is one or more attributes applied to a whole screen — for example, you might apply the stock Android Theme.dialog theme to an activity designed to be a floating dialog box. A theme is assigned as an attribute to an Activity in the manifest file. -
-
- Both styles and themes are defined in a <style> block containing one or more string or numerical values (typically color values), or references to other resources (drawables and so on). These elements support inheritance, so you could have MyBaseTheme, MyBaseTheme.Fancy, MyBaseTheme.Small, and so on.
-
For a complete discussion on styles and themes, read -Applying Styles and Themes.
- -
- Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?> declaration, and a root <resources> element containing one or more <style> tags.
-
- Resource source file location: res/values/styles.xml (file name is arbitrary). The file name is arbitrary, but standard practice is to put all styles into a file named styles.xml. -
-- Compiled resource datatype: Resource pointer to a Java CharSequence. -
-- Resource reference name: -
-R.style.styleID for the whole style, R.style.styleID.itemID for an individual setting
- @[package:]style/styleID for a whole style, @[package:]style/styleID/itemID for an individual item. Note: to refer to a value in the currently applied theme, use "?" instead of "@" as described below (XML).
- - Syntax -
--<style name=string [parent=string] > - <item name=string>Hex value | string value | reference</item>+ -</style> --
android:Theme for the base Android theme, or MyTheme for a theme defined in your package).
- For examples of how to declare and apply styles and themes, read -Applying Styles and Themes.
diff --git a/docs/html/guide/topics/resources/index.jd b/docs/html/guide/topics/resources/index.jd deleted file mode 100644 index 7e3bce42..0000000 --- a/docs/html/guide/topics/resources/index.jd +++ /dev/null @@ -1,40 +0,0 @@ -page.title=Resources and Assets -@jd:body - -Resources are an integral part of an Android application.
-In general, these are external elements that you want to include and reference within your application,
-like images, audio, video, text strings, layouts, themes, etc. Every Android application contains
-a directory for resources (res/) and a directory for assets (assets/).
-Assets are used less often, because their applications are far fewer. You only need to save data
-as an asset when you need to read the raw bites.
-The directories for resources and assets both reside at the top of your project directory, alongside your source code directory
-(src/).
The difference between "resources" and "assets" isn't much on the surface, but in general,
-you'll use resources to store your external content much more often than you'll use assets.
-The real difference is that anything
-placed in the resources directory will be easily accessible from your application from the
-R class, which is compiled by Android. Whereas, anything placed in the assets
-directory will maintain its raw file format and, in order to read it, you must use the
-{@link android.content.res.AssetManager} to read the file as a stream of bytes. So keeping
-files and data in resources (res/) makes them easily accessible.
Within the documents of this topic, you'll find information on the kinds of standard resources -that are typically used in an Android application and how to reference them from you code. -Resources and Internationalization -is where you should start, to learn more about how Android utilizes project resources. Then, the -Available Resource Types -document offers a summary of various resource types and a reference to their specifications. -
diff --git a/docs/html/guide/topics/resources/resources-i18n.jd b/docs/html/guide/topics/resources/resources-i18n.jd deleted file mode 100644 index b1da4cd..0000000 --- a/docs/html/guide/topics/resources/resources-i18n.jd +++ /dev/null @@ -1,704 +0,0 @@ -page.title=Resources and Internationalization -parent.title=Resources and Assets -parent.link=index.html -@jd:body - -Resources are external files (that is, non-code files) that are used by -your code and compiled into your application at build time. Android -supports a number of different kinds of resource files, including XML, -PNG, and JPEG files. The XML files have very different formats depending -on what they describe. This document describes what kinds of files are -supported, and the syntax or format of each.
-Resources are externalized from source code, and XML files are compiled into -a binary, fast loading format for efficiency reasons. Strings, likewise are compressed -into a more efficient storage form. It is for these reasons that we have these -different resource types in the Android platform.
- -This is a fairly technically dense document, and together with the -Available Resources -document, they cover a lot of information about resources. It is not necessary -to know this document by heart to use Android, but rather to know that the -information is here when you need it.
- - -This topic includes a terminology list associated with resources, and a series - of examples of using resources in code. For a complete guide to the supported - Android resource types, see - Available Resources. -
-The Android resource system keeps track of all non-code - assets associated with an application. You use the - {@link android.content.res.Resources Resources} class to access your - application's resources; the Resources instance associated with your - application can generally be found through - {@link android.content.Context#getResources Context.getResources()}.
-An application's resources are compiled into the application -binary at build time for you by the build system. To use a resource, -you must install it correctly in the source tree and build your -application. As part of the build process, symbols for each -of the resources are generated that you can use in your source -code -- this allows the compiler to verify that your application code matches -up with the resources you defined.
- -The rest of this section is organized as a tutorial on how to -use resources in an application.
- - -Android supports string, bitmap, and many other types of resource. The syntax and format -of each, and where they're stored, depends upon the type of object. In -general, though, you create resources from three types of files: XML files -(everything but bitmaps and raw), bitmap files(for images) and Raw files (anything -else, for example sound files, etc.). In fact, there are two different types of -XML file as well, those that get compiled as-is into the package, and those that -are used to generate resources by aapt. Here is a list of each -resource type, the format of the file, a description of the file, and details -of any XML files.
- -You will create and store your resource files under the appropriate
-subdirectory under the res/ directory in your project. Android
-has a resource compiler (aapt) that compiles resources according to which
-subfolder they are in, and the format of the file. Here is a list of the file
-types for each resource. See the
-Available Resources for
-descriptions of each type of object, the syntax, and the format or syntax of
-the containing file.
| Directory | -Resource Types | -
|---|---|
res/anim/ |
- XML files that are compiled into - frame by - frame animation or - tweened - animation objects | -
res/drawable/ |
- .png, .9.png, .jpg files that are compiled into the following - Drawable resource subtypes: -To get a resource of this type, use |
-
res/layout/ |
- XML files that are compiled into screen layouts (or part of a screen). - See Declaring Layout | -
res/values/ |
- XML files that can be compiled into many kinds of resource. -Note: unlike the other res/ folders, this one - can hold any number of files that hold descriptions of resources to create - rather than the resources themselves. The XML element types control - where these resources are placed under the R class. -While the files can be named anything, these are - the typical files in this folder (the convention is to name - the file after the type of elements defined within): -
|
-
res/xml/ |
- Arbitrary XML files that are compiled and can be read at run time by - calling {@link android.content.res.Resources#getXml(int) Resources.getXML()}. | -
res/raw/ |
- Arbitrary files to copy directly to the device. They are added uncompiled - to the compressed file that your application build produces. To use these - resources in your application, call {@link android.content.res.Resources#openRawResource(int) - Resources.openRawResource()} with the resource ID, which is R.raw.somefilename. | -
Resources are compiled into the final APK file. Android creates a wrapper class, - called R, that you can use to refer to these resources in your code. R contains subclasses - named according to the path and file name of the source file
- -This section describes how to use the resources you've created. It includes the - following topics:
-At compile time, Android generates a class named R that contains resource identifiers - to all the resources in your program. This class contains several subclasses, - one for each type of resource supported by Android, and for which you provided - a resource file. Each class contains one or more identifiers for the compiled resources, - that you use in your code to load the resource. Here is a small resource file - that contains string, layout (screens or parts of screens), and image resources.
-Note: the R class is an auto-generated file and is not -designed to be edited by hand. It will be automatically re-created as needed when -the resources are updated.
-package com.android.samples;
-public final class R {
- public static final class string {
- public static final int greeting=0x0204000e;
- public static final int start_button_text=0x02040001;
- public static final int submit_button_text=0x02040008;
- public static final int main_screen_title=0x0204000a;
- };
- public static final class layout {
- public static final int start_screen=0x02070000;
- public static final int new_user_pane=0x02070001;
- public static final int select_user_list=0x02070002;
-
- };
- public static final class drawable {
- public static final int company_logo=0x02020005;
- public static final int smiling_cat=0x02020006;
- public static final int yellow_fade_background=0x02020007;
- public static final int stretch_button_1=0x02020008;
-
- };
-};
-
-
-Using resources in code is just a matter of knowing the full resource ID -and what type of object your resource has been compiled into. Here is the -syntax for referring to a resource:
-R.resource_type.resource_name
or
-android.R.resource_type.resource_name
Where resource_type is the R subclass that holds a specific type
-of resource. resource_name is the name attribute for resources
-defined in XML files, or the file name (without the extension) for resources
-defined by other file types. Each type of resource will be added to a specific
-R subclass, depending on the type of resource it is; to learn which R subclass
-hosts your compiled resource type, consult the
-Available Resources document. Resources compiled by your own application can
-be referred to without a package name (simply as
-R.resource_type.resource_name). Android contains
-a number of standard resources, such as screen styles and button backgrounds. To
-refer to these in code, you must qualify them with android, as in
-android.R.drawable.button_background.
Here are some good and bad examples of using compiled resources in code:
- -// Load a background for the current screen from a drawable resource. -this.getWindow().setBackgroundDrawableResource(R.drawable.my_background_image); - -// WRONG Sending a string resource reference into a -// method that expects a string. -this.getWindow().setTitle(R.string.main_title); - -// RIGHT Need to get the title from the Resources wrapper. -this.getWindow().setTitle(Resources.getText(R.string.main_title)); - -// Load a custom layout for the current screen. -setContentView(R.layout.main_screen); - -// Set a slide in animation for a ViewFlipper object. -mFlipper.setInAnimation(AnimationUtils.loadAnimation(this, - R.anim.hyperspace_in)); - -// Set the text on a TextView object. -TextView msgTextView = (TextView)findViewByID(R.id.msg); -msgTextView.setText(R.string.hello_message);- - -
A value supplied in an attribute (or resource) can also be a reference to -a resource. This is often used in layout files to supply strings (so they -can be localized) and images (which exist in another file), though a reference -can be any resource type including colors and integers.
- -For example, if we have -color -resources, we can write a layout file that sets the text color size to be -the value contained in one of those resources:
- --<?xml version="1.0" encoding="utf-8"?> -<EditText id="text" - xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" android:layout_height="fill_parent" - android:textColor="@color/opaque_red" - android:text="Hello, World!" /> -- -
Note here the use of the '@' prefix to introduce a resource reference -- the
-text following that is the name of a resource in the form
-of @[package:]type/name. In this case we didn't need to specify
-the package because we are referencing a resource in our own package. To
-reference a system resource, you would need to write:
-<?xml version="1.0" encoding="utf-8"?> -<EditText id="text" - xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" android:layout_height="fill_parent" - android:textColor="@android:color/opaque_red" - android:text="Hello, World!" /> -- -
As another example, you should always use resource references when supplying -strings in a layout file so that they can be localized:
- --<?xml version="1.0" encoding="utf-8"?> -<EditText id="text" - xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" android:layout_height="fill_parent" - android:textColor="@android:color/opaque_red" - android:text="@string/hello_world" /> -- -
This facility can also be used to create references between resources. -For example, we can create new drawable resources that are aliases for -existing images:
- --<?xml version="1.0" encoding="utf-8"?> -<resources> - <drawable id="my_background">@android:drawable/theme2_background</drawable> -</resources> -- - -
Another kind of resource value allows you to reference the value of an -attribute in the current theme. This attribute reference can only -be used in style resources and XML attributes; it allows you to customize the -look of UI elements by changing them to standard variations supplied by the -current theme, instead of supplying more concrete values.
- -As an example, we can use this in our layout to set the text color to -one of the standard colors defined in the base system theme:
- --<?xml version="1.0" encoding="utf-8"?> -<EditText id="text" - xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" android:layout_height="fill_parent" - android:textColor="?android:textDisabledColor" - android:text="@string/hello_world" /> -- -
Note that this is very similar to a resource reference, except we are using
-an '?' prefix instead of '@'. When you use this markup, you are supplying
-the name of an attribute resource that will be looked up in the theme --
-because the resource tool knows that an attribute resource is expected,
-you do not need to explicitly state the type (which would be
-?android:attr/android:textDisabledColor).
Other than using this resource identifier to find the value in the
-theme instead of raw resources, the name syntax is identical to the '@' format:
-?[namespace:]type/name with the type here being optional.
Many resources included with the system are available to applications. -All such resources are defined under the class "android.R". For example, -you can display the standard application icon in a screen with the following -code:
- -
-public class MyActivity extends Activity
-{
- public void onStart()
- {
- requestScreenFeatures(FEATURE_BADGE_IMAGE);
-
- super.onStart();
-
- setBadgeResource(android.R.drawable.sym_def_app_icon);
- }
-}
-
-
-In a similar way, this code will apply to your screen the standard -"green background" visual treatment defined by the system:
- -
-public class MyActivity extends Activity
-{
- public void onStart()
- {
- super.onStart();
-
- setTheme(android.R.style.Theme_Black);
- }
-}
-
-
-
-You can supply different resources for your product according to the UI -language or hardware configuration on the device. Note that although you can -include different string, layout, and other resources, the SDK does not expose -methods to let you specify which alternate resource set to load. Android -detects the proper set for the hardware and location, and loads them as -appropriate. Users can select alternate language settings using the settings -panel on the device.
-To include alternate resources, create parallel resource folders with -qualifiers appended to the folder names, indicating the configuration it -applies to (language, screen orientation, and so on). For example, here is a -project that holds one string resource file for English, and another for -French:
- --MyApp/ - res/ - values-en/ - strings.xml - values-fr/ - strings.xml -- -
Android supports several types of qualifiers, with various values for each. -Append these to the end of the resource folder name, separated by dashes. You -can add multiple qualifiers to each folder name, but they must appear in the -order they are listed here. For example, a folder containing drawable -resources for a fully specified configuration would look like:
- --MyApp/ - res/ - drawable-en-rUS-port-160dpi-finger-keysexposed-qwerty-dpad-480x320/ -- -
More typically, you will only specify a few specific configuration options -that a resource is defined for. You may drop any of the values from the -complete list, as long as the remaining values are still in the same -order:
- --MyApp/ - res/ - drawable-en-rUS-finger/ - drawable-port/ - drawable-port-160dpi/ - drawable-qwerty/ -- -
| Qualifier | -Values | -
|---|---|
| Language | -The two letter ISO
- 639-1 language code in lowercase. For example:
- en, fr, es |
-
| Region | -The two letter
- ISO
- 3166-1-alpha-2 language code in uppercase preceded by a lowercase
- "r". For example: rUS, rFR, rES |
-
| Screen orientation | -port, land, square |
-
| Screen pixel density | -92dpi, 108dpi, etc. |
-
| Touchscreen type | -notouch, stylus, finger |
-
| Whether the keyboard is available to the user | -keysexposed, keyshidden |
-
| Primary text input method | -nokeys, qwerty, 12key |
-
| Primary non-touchscreen - navigation method |
- nonav, dpad, trackball, wheel |
-
| Screen dimensions | -320x240, 640x480, etc. The larger dimension
- must be specified first. |
-
This list does not include device-specific parameters such as carrier, -branding, device/hardware, or manufacturer. Everything that an application -needs to know about the device that it is running on is encoded via the -resource qualifiers in the table above.
- -Here are some general guidelines on qualified resource directory names:
- -drawable directory must be named
- drawable-port, not drawable-PORT.drawable-port
- and drawable-PORT, even if you had intended "port" and
- "PORT" to refer to different parameter values.drawable-rEN-rFR/)drawable-en-rUS-land will apply to landscape view,
- US-English devices. res/ folder.
- Qualified directories cannot be nested (you cannot have res/drawable/drawable-en) MyApp/res/drawable-port-92dp/myimage.pngR.drawable.myimage (code)@drawable/myimage (XML)Android will pick which of the various underlying resource files should be -used at runtime, depending on the current configuration. The selection process -is as follows:
- -MyApp/res/drawable-port-92dpi/.
- ---MyApp/res/drawable/myimage.png -MyApp/res/drawable-en/myimage.png -MyApp/res/drawable-port/myimage.png --MyApp/res/drawable-port-92dpi/myimage.png-
MyApp/res/drawable-en/ and MyApp/res/drawable-port/.
- The directory MyApp/res/drawable/ is eliminated because
- it has zero matching configurations, while the others have one matching
- configuration.
- ----MyApp/res/drawable/myimage.png-MyApp/res/drawable-en/myimage.png -MyApp/res/drawable-port/myimage.png -
MyApp/res/drawable-en/.
- --MyApp/res/drawable-en/myimage.png --MyApp/res/drawable-port/myimage.png-
The resource system brings a number of different pieces together to -form the final complete resource functionality. To help understand the -overall system, here are some brief definitions of the core concepts and -components you will encounter in using it:
- -Asset: A single blob of data associated with an application. This -includes object files compiled from the Java source code, graphics (such as PNG -images), XML files, etc. These files are organized in a directory hierarchy -that, during final packaging of the application, is bundled together into a -single ZIP file.
- -aapt: Android Asset Packaging Tool. The tool that generates the -final ZIP file of application assets. In addition to collecting raw assets -together, it also parses resource definitions into binary asset data.
- -Resource Table: A special asset that aapt generates for you, -describing all of the resources contained in an application/package. -This file is accessed for you by the Resources class; it is not touched -directly by applications.
- -Resource: An entry in the Resource Table describing a single -named value. Broadly, there are two types of resources: primitives and -bags.
- -Resource Identifier: In the Resource Table all resources are -identified by a unique integer number. In source code (resource descriptions, -XML files, Java source code) you can use symbolic names that stand as constants for -the actual resource identifier integer.
- -Primitive Resource: All primitive resources can be written as a -simple string, using formatting to describe a variety of primitive types -included in the resource system: integers, colors, strings, references to -other resources, etc. Complex resources, such as bitmaps and XML -describes, are stored as a primitive string resource whose value is the path -of the underlying Asset holding its actual data.
- -Bag Resource: A special kind of resource entry that, instead of a -simple string, holds an arbitrary list of name/value pairs. Each name is -itself a resource identifier, and each value can hold -the same kinds of string formatted data as a normal resource. Bags also -support inheritance: a bag can inherit the values from another bag, selectively -replacing or extending them to generate its own contents.
- -Kind: The resource kind is a way to organize resource identifiers -for various purposes. For example, drawable resources are used to -instantiate Drawable objects, so their data is a primitive resource containing -either a color constant or string path to a bitmap or XML asset. Other -common resource kinds are string (localized string primitives), color -(color primitives), layout (a string path to an XML asset describing a view -layout), and style (a bag resource describing user interface attributes). -There is also a standard "attr" resource kind, which defines the resource -identifiers to be used for naming bag items and XML attributes
- -Style: The name of the resource kind containing bags that are used -to supply a set of user interface attributes. For example, a TextView class may -be given a style resource that defines its text size, color, and alignment. -In a layout XML file, you associate a style with a bag using the "style" -attribute, whose value is the name of the style resource.
- -Style Class: Specifies a related set of attribute resources. -This data is not placed in the resource table itself, but used to generate -constants in the source code that make it easier for you to retrieve values out of -a style resource and/or XML tag's attributes. For example, the -Android platform defines a "View" style class that -contains all of the standard view attributes: padding, visibility, -background, etc.; when View is inflated it uses this style class to -retrieve those values from the XML file (at which point style and theme -information is applied as approriate) and load them into its instance.
- -Configuration: For any particular resource identifier, there may be -multiple different available values depending on the current configuration. -The configuration includes the locale (language and country), screen -orientation, screen density, etc. The current configuration is used to -select which resource values are in effect when the resource table is -loaded.
- -Theme: A standard style resource that supplies global -attribute values for a particular context. For example, when writing an -Activity the application developer can select a standard theme to use, such -as the Theme.White or Theme.Black styles; this style supplies information -such as the screen background image/color, default text color, button style, -text editor style, text size, etc. When inflating a layout resource, most -values for widgets (the text color, selector, background) if not explicitly -set will come from the current theme; style and attribute -values supplied in the layout can also assign their value from explicitly -named values in the theme attributes if desired.
- -Overlay: A resource table that does not define a new set of resources, -but instead replaces the values of resources that are in another resource table. -Like a configuration, this is applied at load time -to the resource data; it can add new configuration values (for example -strings in a new locale), replace existing values (for example change -the standard white background image to a "Hello Kitty" background image), -and modify resource bags (for example change the font size of the Theme.White -style to have an 18 pt font size). This is the facility that allows the -user to select between different global appearances of their device, or -download files with new appearances.
- -The Available Resources -document provides a detailed list of the various types of resource and how to use them -from within the Java source code, or from other references.
- - -Coming Soon: Internationalization and Localization are -critical, but are also not quite ready yet in the current SDK. As the -SDK matures, this section will contain information on the Internationalization -and Localization features of the Android platform. In the meantime, it is a good -idea to start by externalizing all strings, and practicing good structure in -creating and using resources.
- diff --git a/docs/html/guide/topics/security/security.jd b/docs/html/guide/topics/security/security.jd deleted file mode 100644 index da201c4..0000000 --- a/docs/html/guide/topics/security/security.jd +++ /dev/null @@ -1,397 +0,0 @@ -page.title=Security and Permissions -@jd:body - -Android is a multi-process system, in which each application (and parts of the -system) runs in its own process. Most security between applications and -the system is enforced at the process level through standard Linux facilities, -such as user and group IDs that are assigned to applications. -Additional finer-grained security features are provided -through a "permission" mechanism that enforces restrictions on the specific -operations that a particular process can perform, and per-URI permissions -for granting ad-hoc access to specific pieces of data.
- - -A central design point of the Android security architecture is that no -application, by default, has permission to perform any operations that would -adversely impact other applications, the operating system, or the user. This -includes reading or writing the user's private data (such as contacts or -e-mails), reading or writing another application's files, performing -network access, keeping the device awake, etc.
- -
An application's process is a secure sandbox. It can't disrupt other -applications, except by explicitly declaring the permissions it needs -for additional capabilities not provided by the basic sandbox. These -permissions it requests can be handled by the operating in various ways, -typically by automatically allowing or disallowing based on certificates or -by prompting the user. The permissions required by an application are declared -statically in that application, so they can be known up-front at install time -and will not change after that.
- - - -All Android applications (.apk files) must be signed with a certificate whose -private key is held by their developer. This certificate identifies the author -of the application. The certificate does not need to be signed by -a certificate authority: it is perfectly allowable, and typical, for Android -applications to use self-signed certificates. The certificate is used only -to establish trust relationships between applications, not for wholesale -control over whether an application can be installed. The most significant -ways that signatures impact security is by determining who can access -signature-based permissions and who can share user IDs.
- - - -Each Android package (.apk) file installed on the device is given its -own unique Linux user ID, creating a sandbox for it and preventing it from touching -other applications (or other applications from touching it). This user ID is -assigned to it when the application is installed on the device, and -remains constant for the duration of its life on that device.
- -Because security enforcement happens at the
-process level, the code of any two packages can not normally
-run in the same process, since they need to run as different Linux users.
-You can use the {@link android.R.attr#sharedUserId} attribute in the
-AndroidManifest.xml's
-{@link android.R.styleable#AndroidManifest manifest} tag of each package to
-have them assigned the same user ID. By doing this, for purposes of security
-the two packages are then treated as being the same application, with the same
-user ID and file permissions. Note that in order to retain security, only two applications
-signed with the same signature (and requesting the same sharedUserId) will
-be given the same user ID.
Any data stored by an application will be assigned that application's user -ID, and not normally accessible to other packages. When creating a new file -with {@link android.content.Context#getSharedPreferences}, -{@link android.content.Context#openFileOutput}, or -{@link android.content.Context#openOrCreateDatabase}, -you can use the -{@link android.content.Context#MODE_WORLD_READABLE} and/or -{@link android.content.Context#MODE_WORLD_WRITEABLE} flags to allow any other -package to read/write the file. When setting these flags, the file is still -owned by your application, but its global read and/or write permissions have -been set appropriately so any other application can see it.
- - - -A basic Android application has no permissions associated with it,
-meaning it can not do anything that would adversely impact the user experience
-or any data on the device. To make use of protected features of the device,
-you must include in your AndroidManifest.xml one or more
-{@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}
-tags declaring the permissions that your application needs.
For example, an application that needs to monitor incoming SMS messages would -specify:
- -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.android.app.myapp" > - - <uses-permission android:name="android.permission.RECEIVE_SMS" /> - -</manifest>- -
At application install time, permissions requested by the application are -granted to it by the package installer, based on checks against the -signatures of the applications declaring those permissions and/or interaction -with the user. No checks with the user -are done while an application is running: it either was granted a particular -permission when installed, and can use that feature as desired, or the -permission was not granted and any attempt to use the feature will fail -without prompting the user.
- -Often times a permission failure will result in a {@link -java.lang.SecurityException} being thrown back to the application. However, -this is not guaranteed to occur everywhere. For example, the {@link -android.content.Context#sendBroadcast} method checks permissions as data is -being delivered to each receiver, after the method call has returned, so you -will not receive an exception if there are permission failures. In almost all -cases, however, a permission failure will be printed to the system log.
- -The permissions provided by the Android system can be found at {@link -android.Manifest.permission}. Any application may also define and enforce its -own permissions, so this is not a comprehensive list of all possible -permissions.
- -A particular permission may be enforced at a number of places during your -program's operation:
- -To enforce your own permissions, you must first declare them in your
-AndroidManifest.xml using one or more
-{@link android.R.styleable#AndroidManifestPermission <permission>}
-tags.
For example, an application that wants to control who can start one -of its activities could declare a permission for this operation as follows:
- -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.me.app.myapp" > - - <permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY" - android:label="@string/permlab_deadlyActivity" - android:description="@string/permdesc_deadlyActivity" - android:permissionGroup="android.permission-group.COST_MONEY" - android:protectionLevel="dangerous" /> - -</manifest>- -
The {@link android.R.styleable#AndroidManifestPermission_protectionLevel -<protectionLevel>} attribute is required, telling the system how the -user is to be informed of applications requiring the permission, or who is -allowed to hold that permission, as described in the linked documentation.
- -The {@link android.R.styleable#AndroidManifestPermission_permissionGroup -<permissionGroup>} attribute is optional, and only used to help the system display -permissions to the user. You will usually want to set this to either a standard -system group (listed in {@link android.Manifest.permission_group -android.Manifest.permission_group}) or in more rare cases to one defined by -yourself. It is preferred to use an existing group, as this simplifies the -permission UI shown to the user.
- -Note that both a label and description should be supplied for the
-permission. These are string resources that can be displayed to the user when
-they are viewing a list of permissions
-({@link android.R.styleable#AndroidManifestPermission_label android:label})
-or details on a single permission (
-{@link android.R.styleable#AndroidManifestPermission_description android:description}).
-The label should be short, a few words
-describing the key piece of functionality the permission is protecting. The
-description should be a couple sentences describing what the permission allows
-a holder to do. Our convention for the description is two sentences, the first
-describing the permission, the second warning the user of what bad things
-can happen if an application is granted the permission.
Here is an example of a label and description for the CALL_PHONE -permission:
- -- <string name="permlab_callPhone">directly call phone numbers</string> - <string name="permdesc_callPhone">Allows the application to call - phone numbers without your intervention. Malicious applications may - cause unexpected calls on your phone bill. Note that this does not - allow the application to call emergency numbers.</string> -- -
You can look at the permissions currently defined in the system with the
-shell command adb shell pm list permissions. In particular,
-the '-s' option displays the permissions in a form roughly similar to how the
-user will see them:
-$ adb shell pm list permissions -s -All Permissions: - -Network communication: view Wi-Fi state, create Bluetooth connections, full -Internet access, view network state - -Your location: access extra location provider commands, fine (GPS) location, -mock location sources for testing, coarse (network-based) location - -Services that cost you money: send SMS messages, directly call phone numbers - -...- - -
High-level permissions restricting access to entire components of the
-system or application can be applied through your
-AndroidManifest.xml. All that this requires is including an {@link
-android.R.attr#permission android:permission} attribute on the desired
-component, naming the permission that will be used to control access to
-it.
{@link android.app.Activity} permissions -(applied to the -{@link android.R.styleable#AndroidManifestActivity <activity>} tag) -restrict who can start the associated -activity. The permission is checked during -{@link android.content.Context#startActivity Context.startActivity()} and -{@link android.app.Activity#startActivityForResult Activity.startActivityForResult()}; -if the caller does not have -the required permission then {@link java.lang.SecurityException} is thrown -from the call.
- -{@link android.app.Service} permissions -(applied to the -{@link android.R.styleable#AndroidManifestService <service>} tag) -restrict who can start or bind to the -associated service. The permission is checked during -{@link android.content.Context#startService Context.startService()}, -{@link android.content.Context#stopService Context.stopService()} and -{@link android.content.Context#bindService Context.bindService()}; -if the caller does not have -the required permission then {@link java.lang.SecurityException} is thrown -from the call.
- -{@link android.content.BroadcastReceiver} permissions -(applied to the -{@link android.R.styleable#AndroidManifestReceiver <receiver>} tag) -restrict who can send broadcasts to the associated receiver. -The permission is checked after -{@link android.content.Context#sendBroadcast Context.sendBroadcast()} returns, -as the system tries -to deliver the submitted broadcast to the given receiver. As a result, a -permission failure will not result in an exception being thrown back to the -caller; it will just not deliver the intent. In the same way, a permission -can be supplied to -{@link android.content.Context#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter, String, android.os.Handler) -Context.registerReceiver()} -to control who can broadcast to a programmatically registered receiver. -Going the other way, a permission can be supplied when calling -{@link android.content.Context#sendBroadcast(Intent, String) Context.sendBroadcast()} -to restrict which BroadcastReceiver objects are allowed to receive the broadcast (see -below).
- -{@link android.content.ContentProvider} permissions -(applied to the -{@link android.R.styleable#AndroidManifestProvider <provider>} tag) -restrict who can access the data in -a {@link android.content.ContentProvider}. (Content providers have an important -additional security facility available to them called -URI permissions which is described later.) -Unlike the other components, -there are two separate permission attributes you can set: -{@link android.R.attr#readPermission android:readPermission} restricts who -can read from the provider, and -{@link android.R.attr#writePermission android:writePermission} restricts -who can write to it. Note that if a provider is protected with both a read -and write permission, holding only the write permission does not mean -you can read from a provider. The permissions are checked when you first -retrieve a provider (if you don't have either permission, a SecurityException -will be thrown), and as you perform operations on the provider. Using -{@link android.content.ContentResolver#query ContentResolver.query()} requires -holding the read permission; using -{@link android.content.ContentResolver#insert ContentResolver.insert()}, -{@link android.content.ContentResolver#update ContentResolver.update()}, -{@link android.content.ContentResolver#delete ContentResolver.delete()} -requires the write permission. -In all of these cases, not holding the required permission results in a -{@link java.lang.SecurityException} being thrown from the call.
- - - -In addition to the permission enforcing who can send Intents to a -registered {@link android.content.BroadcastReceiver} (as described above), you -can also specify a required permission when sending a broadcast. By calling {@link -android.content.Context#sendBroadcast(android.content.Intent,String) -Context.sendBroadcast()} with a -permission string, you require that a receiver's application must hold that -permission in order to receive your broadcast.
- -Note that both a receiver and a broadcaster can require a permission. When -this happens, both permission checks must pass for the Intent to be delivered -to the associated target.
- - - -Arbitrarily fine-grained permissions can be enforced at any call into a -service. This is accomplished with the {@link -android.content.Context#checkCallingPermission Context.checkCallingPermission()} -method. Call with a desired -permission string and it will return an integer indicating whether that -permission has been granted to the current calling process. Note that this can -only be used when you are executing a call coming in from another process, -usually through an IDL interface published from a service or in some other way -given to another process.
- -There are a number of other useful ways to check permissions. If you have -the pid of another process, you can use the Context method {@link -android.content.Context#checkPermission(String, int, int) Context.checkPermission(String, int, int)} -to check a permission against that pid. If you have the package name of another -application, you can use the direct PackageManager method {@link -android.content.pm.PackageManager#checkPermission(String, String) -PackageManager.checkPermission(String, String)} -to find out whether that particular package has been granted a specific permission.
- - - -The standard permission system described so far is often not sufficient -when used with content providers. A content provider may want to -protect itself with read and write permissions, while its direct clients -also need to hand specific URIs to other applications for them to operate on. -A typical example is attachments in a mail application. Access to the mail -should be protected by permissions, since this is sensitive user data. However, -if a URI to an image attachment is given to an image viewer, that image viewer -will not have permission to open the attachment since it has no reason to hold -a permission to access all e-mail.
- -The solution to this problem is per-URI permissions: when starting an -activity or returning a result to an activity, the caller can set -{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION -Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or -{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION -Intent.FLAG_GRANT_WRITE_URI_PERMISSION}. This grants the receiving activity -permission access the specific data URI in the Intent, regardless of whether -it has any permission to access data in the content provider corresponding -to the Intent.
- -This mechanism allows a common capability-style model where user interaction -(opening an attachment, selecting a contact from a list, etc) drives ad-hoc -granting of fine-grained permission. This can be a key facility for reducing -the permissions needed by applications to only those directly related to their -behavior.
- -The granting of fine-grained URI permissions does, however, require some -cooperation with the content provider holding those URIs. It is strongly -recommended that content providers implement this facility, and declare that -they support it through the -{@link android.R.styleable#AndroidManifestProvider_grantUriPermissions -android:grantUriPermissions} attribute or -{@link android.R.styleable#AndroidManifestGrantUriPermission -<grant-uri-permissions>} tag.
- -More information can be found in the -{@link android.content.Context#grantUriPermission Context.grantUriPermission()}, -{@link android.content.Context#revokeUriPermission Context.revokeUriPermission()}, and -{@link android.content.Context#checkUriPermission Context.checkUriPermission()} -methods.
- diff --git a/docs/html/guide/topics/sensors/accelerometer.jd b/docs/html/guide/topics/sensors/accelerometer.jd deleted file mode 100644 index da760bc..0000000 --- a/docs/html/guide/topics/sensors/accelerometer.jd +++ /dev/null @@ -1,18 +0,0 @@ -page.title=Accelerometer -parent.title=Sensors -parent.link=index.html -@jd:body - -The accelerometer sensors allow you to detect the various movements of the device.
- -The compass provides data on the devices current polar orientation.
\ No newline at end of file diff --git a/docs/html/guide/topics/ui/binding.jd b/docs/html/guide/topics/ui/binding.jd deleted file mode 100644 index 85aed18..0000000 --- a/docs/html/guide/topics/ui/binding.jd +++ /dev/null @@ -1,113 +0,0 @@ -page.title=Binding to Data with AdapterView -parent.title=User Interface -parent.link=index.html -@jd:body - -The {@link android.widget.AdapterView} is a ViewGroup subclass whose child Views are determined by an {@link android.widget.Adapter Adapter} that -binds to data of some type. AdapterView is useful whenever you need to display stored data (as opposed to resource strings or drawables) in your layout.
- -{@link android.widget.Gallery Gallery}, {@link android.widget.ListView ListView}, and {@link android.widget.Spinner Spinner} are examples of AdapterView subclasses that you can use to bind to a specific type of data and display it in a certain way.
- - -AdapterView objects have two main responsibilities:
-Inserting data into the layout is typically done by binding the AdapterView class to an {@link -android.widget.Adapter}, which retireves data from an external source (perhaps a list that -the code supplies or query results from the device's database).
-The following code sample does the following:
--// Get a Spinner and bind it to an ArrayAdapter that -// references a String array. -Spinner s1 = (Spinner) findViewById(R.id.spinner1); -ArrayAdapter- -adapter = ArrayAdapter.createFromResource( - this, R.array.colors, android.R.layout.simple_spinner_item); -adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); -s1.setAdapter(adapter); - -// Load a Spinner and bind it to a data query. -private static String[] PROJECTION = new String[] { - People._ID, People.NAME - }; - -Spinner s2 = (Spinner) findViewById(R.id.spinner2); -Cursor cur = managedQuery(People.CONTENT_URI, PROJECTION, null, null); - -SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this, - android.R.layout.simple_spinner_item, // Use a template - // that displays a - // text view - cur, // Give the cursor to the list adatper - new String[] {People.NAME}, // Map the NAME column in the - // people database to... - new int[] {android.R.id.text1}); // The "text1" view defined in - // the XML template - -adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); -s2.setAdapter(adapter2); -
Note that it is necessary to have the People._ID column in projection used with CursorAdapter -or else you will get an exception.
- -If, during the course of your application's life, you change the underlying data that is read by your Adapter, -you should call {@link android.widget.ArrayAdapter#notifyDataSetChanged()}. This will notify the attached View -that the data has been changed and it should refresh itself.
- -You handle the user's selecction by setting the class's {@link -android.widget.AdapterView.OnItemClickListener} member to a listener and -catching the selection changes.
-
-// Create a message handling object as an anonymous class.
-private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
- public void onItemClick(AdapterView parent, View v, int position, long id)
- {
- // Display a messagebox.
- Toast.makeText(mContext,"You've got an event",Toast.LENGTH_SHORT).show();
- }
-};
-
-// Now hook into our object and set its onItemClickListener member
-// to our class handler object.
-mHistoryView = (ListView)findViewById(R.id.history);
-mHistoryView.setOnItemClickListener(mMessageClickedHandler);
-
-
-For more discussion on how to create different AdapterViews, read the following tutorials: -Hello Spinner, -Hello ListView, and -Hello GridView. -
Android offers a sophisticated and powerful componentized model for building your UI, -based on the fundamental layout classes: {@link android.view.View} and -{@link android.view.ViewGroup}. To start with, the platform includes a variety of prebuilt -View and ViewGroup subclasses — called widgets and layouts, respectively — -that you can use to construct your UI.
- -A partial list of available widgets includes {@link android.widget.Button Button}, -{@link android.widget.TextView TextView}, -{@link android.widget.EditText EditText}, -{@link android.widget.ListView ListView}, -{@link android.widget.CheckBox CheckBox}, -{@link android.widget.RadioButton RadioButton}, -{@link android.widget.Gallery Gallery}, -{@link android.widget.Spinner Spinner}, and the more special-purpose -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, -{@link android.widget.ImageSwitcher ImageSwitcher}, and -{@link android.widget.TextSwitcher TextSwitcher}.
- -Among the layouts available are {@link android.widget.LinearLayout LinearLayout}, -{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.AbsoluteLayout AbsoluteLayout}, -and others. For more examples, see Common Layout Objects.
- -If none of the prebuilt widgets or layouts meets your needs, you can create your own View subclass. -If you only need to make small adjustments to an existing widget or layout, you can simply subclass -the widget or layout and override its methods. -
- -Creating your own View subclasses gives you precise control over the appearance and function -of a screen element. To give an idea of the control you get with custom views, here are some -examples of what you could do with them:
- --The sections below explain how to create custom Views and use them in your application. -For detailed reference information, see the {@link android.view.View} class.
- - -Here is a high level overview of what you need to know to get started in creating your own -View components:
- -on', for
- example, {@link android.view.View#onDraw onDraw()},
- {@link android.view.View#onMeasure onMeasure()}, and
- {@link android.view.View#onKeyDown onKeyDown()}.
- This is similar to the on... events in {@link android.app.Activity Activity}
- or {@link android.app.ListActivity ListActivity}
- that you override for lifecycle and other functionality hooks.
- Tip: - Extension classes can be defined as inner classes inside the activities - that use them. This is useful because it controls access to them but - isn't necessary (perhaps you want to create a new public View for - wider use in your application). -
- - - --Fully customized components can be used to create graphical components that -appear however you wish. Perhaps a graphical VU -meter that looks like an old analog gauge, or a sing-a-long text view where -a bouncing ball moves along the words so you can sing along with a karaoke -machine. Either way, you want something that the built-in components just -won't do, no matter how you combine them.
-Fortunately, you can easily create components that look and behave in any -way you like, limited perhaps only by your imagination, the size of the -screen, and the available processing power (remember that ultimately your -application might have to run on something with significantly less power -than your desktop workstation).
-To create a fully customized component:
-onMeasure() and
- are also likely to need to override onDraw() if you want
- the component to show something. While both have default behavior,
- the default onDraw() will do nothing, and the default
- onMeasure() will always set a size of 100x100 — which is
- probably not what you want.
- on... methods may also be overridden as required.
- onDraw() and onMeasure()The onDraw() method delivers you a {@link android.graphics.Canvas Canvas}
-upon which you can implement anything you want: 2D graphics, other standard or
-custom components, styled text, or anything else you can think of.
Note: -This does not apply to 3D graphics. If you want to -use 3D graphics, you must extend {@link android.view.SurfaceView SurfaceView} -instead of View, and draw from a seperate thread. See the -GLSurfaceViewActivity sample -for details.
- -onMeasure() is a little more involved. onMeasure()
-is a critical piece of the rendering contract between your component and its
-container. onMeasure() should be overridden to efficiently and
-accurately report the measurements of its contained parts. This is made
-slightly more complex by the requirements of limits from the parent
-(which are passed in to the onMeasure() method) and by the
-requirement to call the setMeasuredDimension() method with the
-measured width and height once they have been calculated. If you fail to
-call this method from an overridden onMeasure() method, the
-result will be an exception at measurement time.
At a high level, implementing onMeasure() looks something
- like this:
onMeasure() method is called with width and
- height measure specifications (widthMeasureSpec and
- heightMeasureSpec parameters, both are integer codes
- representing dimensions) which should be treated as requirements for
- the restrictions on the width and height measurements you should produce. A
- full reference to the kind of restrictions these specifications can require
- can be found in the reference documentation under {@link
- android.view.View#onMeasure View.onMeasure(int, int)} (this reference
- documentation does a pretty good job of explaining the whole measurement
- operation as well).
- onMeasure() method should calculate a
- measurement width and height which will be required to render the
- component. It should try to stay within the specifications passed in,
- although it can choose to exceed them (in this case, the parent can
- choose what to do, including clipping, scrolling, throwing an exception,
- or asking the onMeasure() to try again, perhaps with
- different measurement specifications).
- setMeasuredDimension(int
- width, int height) method must be called with the calculated
- measurements. Failure to do this will result in an exception being
- thrown.
- -Here's a summary of some of the other standard methods that the framework calls on views: -
-| Category | Methods | Description |
|---|---|---|
| Creation | -Constructors | -There is a form of the constructor that are called when the view - is created from code and a form that is called when the view is - inflated from a layout file. The second form should parse and apply - any attributes defined in the layout file. - | -
{@link android.view.View#onFinishInflate()} |
- Called after a view and all of its children has been inflated - from XML. | -|
| Layout | -{@link android.view.View#onMeasure} |
- Called to determine the size requirements for this view and all - of its children. - | -
{@link android.view.View#onLayout} |
- Called when this view should assign a size and position to all - of its children. - | -|
{@link android.view.View#onSizeChanged} |
- Called when the size of this view has changed. - | -|
| Drawing | -{@link android.view.View#onDraw} |
- Called when the view should render its content. - | -
| Event processing | -{@link android.view.View#onKeyDown} |
- Called when a new key event occurs. - | -
{@link android.view.View#onKeyUp} |
- Called when a key up event occurs. - | -|
{@link android.view.View#onTrackballEvent} |
- Called when a trackball motion event occurs. - | -|
{@link android.view.View#onTouchEvent} |
- Called when a touch screen motion event occurs. - | -|
| Focus | -{@link android.view.View#onFocusChanged} |
- Called when the view gains or loses focus. - | -
{@link android.view.View#onWindowFocusChanged} |
- Called when the window containing the view gains or loses focus. - | -|
| Attaching | -{@link android.view.View#onAttachedToWindow()} |
- Called when the view is attached to a window. - | -
{@link android.view.View#onDetachedFromWindow} |
- Called when the view is detached from its window. - | -|
{@link android.view.View#onWindowVisibilityChanged} |
- Called when the visibility of the window containing the view - has changed. - | -
The CustomView sample in the -API Demos provides an example -of a customized View. The custom View is defined in the -LabelView -class.
-The LabelView sample demonstrates a number of different aspects of custom components:
-setText(), setTextSize(),
- setTextColor() and so on.onMeasure method to determine and set the
- rendering size of the component. (Note that in LabelView, the real work is done
- by a private measureWidth() method.)onDraw() method to draw the label onto the
- provided canvas.You can see some sample usages of the LabelView custom View in
-custom_view_1.xml
-from the samples. In particular, you can see a mix of both android:
-namespace parameters and custom app: namespace parameters. These
-app: parameters are the custom ones that the LabelView recognizes
-and works with, and are defined in a styleable inner class inside of the
-samples R resources definition class.
If you don't want to create a completely customized component, but instead -are looking to put together a reusable component that consists of a group of -existing controls, then creating a Compound Component (or Compound Control) might -fit the bill. In a nutshell, this brings together a number of more atomic -controls (or views) into a logical group of items that can be treated as a -single thing. For example, a Combo Box can be thought of as a -combination of a single line EditText field and an adjacent button with an attached - PopupList. If you press the button and select -something from the list, it populates the EditText field, but the user can -also type something directly into the EditText if they prefer.
-In Android, there are actually two other Views readily available to do -this: {@link android.widget.Spinner Spinner} and -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, but -regardless, the concept of a Combo Box makes an easy-to-understand -example.
-To create a compound component:
-onDraw() and onMeasure() methods since the
- layout will have default behavior that will likely work just fine. However,
- you can still override them if you need to.
- on... methods, like
- onKeyDown(), to perhaps choose certain default values from
- the popup list of a combo box when a certain key is pressed.
- - To summarize, the use of a Layout as the basis for a Custom Control has a -number of advantages, including:
- -onDraw() and onMeasure() methods (plus
- most of the other on... methods) will likely have suitable behavior so
- you don't have to override them.
- In the API Demos project
- that comes with the SDK, there are two List
- examples — Example 4 and Example 6 under Views/Lists demonstrate a
- SpeechView which extends LinearLayout to make a component for displaying
- Speech quotes. The corresponding classes in the sample code are
- List4.java and List6.java.
There is an even easier option for creating a custom View which is -useful in certain circumstances. If there is a component that is already very -similar to what you want, you can simply extend that component and just -override the behavior that you want to change. You can do all of the things -you would do with a fully customized component, but by starting with a more -specialized class in the View heirarchy, you can also get a lot of behavior for -free that probably does exactly what you want.
-For example, the SDK includes a NotePad application in the -samples. This demonstrates many aspects of using the Android platform, among -them is extending an EditText View to make a lined notepad. This is not a -perfect example, and the APIs for doing this might change from this early -preview, but it does demonstrate the principles.
-If you haven't done so already, import the
-NotePad sample into Eclipse (or
-just look at the source using the link provided). In particular look at the definition of
-MyEditText in the NoteEditor.java
-file.
Some points to note here
-The class is defined with the following line:
- public static class MyEditText extends EditText
NoteEditor
- activity, but it is public so that it could be accessed as
- NoteEditor.MyEditText from outside of the NoteEditor
- class if desired.
- static, meaning it does not generate the so-called
- "synthetic methods" that allow it to access data from the parent
- class, which in turn means that it really behaves as a separate
- class rather than something strongly related to NoteEditor.
- This is a cleaner way to create inner classes if they do not need
- access to state from the outer class, keeps the generated class
- small, and allows it to be used easily from other classes.
- EditText, which is the View we have chosen to
- customize in this case. When we are finished, the new class will be
- able to substitute for a normal EditText view.
- As always, the super is called first. Furthermore, - this is not a default constructor, but a parameterized one. The - EditText is created with these parameters when it is inflated from an - XML layout file, thus, our constructor needs to both take them and pass them - to the superclass constructor as well.
-In this example, there is only one method to be overridden:
- onDraw() — but there could easily be others needed when you
- create your own custom components.
For the NotePad sample, overriding the onDraw() method allows
- us to paint the blue lines on the EditText view canvas (the
- canvas is passed into the overridden onDraw() method). The
- super.onDraw() method is called before the method ends. The
- superclass method should be invoked, but in this case, we do it at the
- end after we have painted the lines we want to include.
We now have our custom component, but how can we use it? In the
- NotePad example, the custom component is used directly from the
- declarative layout, so take a look at note_editor.xml in the
- res/layout folder.
-<view - class="com.android.notepad.NoteEditor$MyEditText" - id="@+id/note" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:background="@android:drawable/empty" - android:padding="10dip" - android:scrollbars="vertical" - android:fadingEdge="vertical" /> -- -
NoteEditor$MyEditText notation which is a standard way to
- refer to inner classes in the Java programming language.
- If your custom View component is not defined as an inner class, then you can,
- alternatively, declare the View component
- with the XML element name, and exclude the class attribute. For example:
-<com.android.notepad.MyEditText - id="@+id/note" - ... /> --
Notice that the MyEditText class is now a separate class file. When the class
- is nested in the NoteEditor class, this technique will not work.
And that's all there is to it. Admittedly this is a simple case, but -that's the point — creating custom components is only as complicated as you -need it to be.
-A more sophisticated component may override even more on... methods and
-introduce some of its own helper methods, substantially customizing its properties and
-behavior. The only limit is your imagination and what you need the component to
-do.
Your layout is the architecture for the user interface in an Activity. -It defines the layout structure and holds all the elements that appear to the user. -You can declare your layout in two ways:
-The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.
- -The Android Development Tools - (ADT) plugin for Eclipse offers a layout preview of your XML — - with the XML file opened, select the Layout tab.
-You should also try the - Hierarchy Viewer tool, - for debugging layouts — it reveals layout property values, - draws wireframes with padding/margin indicators, and full rendered views while - you debug on the emulator or device.
-The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML. If you're -interested in instantiating View objects at runtime, refer to the {@link android.view.ViewGroup} and -{@link android.view.View} class references.
- -In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element. However, note that not all vocabulary is identical. In some cases, there are slight naming differences. For
-example, the EditText element has a text attribute that corresponds to
-EditText.setText().
Tip: Learn more about different layout types in Common -Layout Objects. There are also a collection of tutorials on building various layouts in the -Hello Views tutorial guide.
- -For your convenience, the API reference documentation for UI related classes lists the available XML attributes that correspond to the class methods, including inherited attributes.
-To learn more about the available XML elements and attributes, as well as the format of the XML file, see Layout Resources.
-Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements.
- -Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. For example, here's an XML layout that uses a vertical {@link android.widget.LinearLayout} -to hold a {@link android.widget.TextView} and a {@link android.widget.Button}:
--<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:orientation="vertical" > - <TextView android:id="@+id/text" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Hello, I am a TextView" /> - <Button android:id="@+id/button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Hello, I am a Button" /> -</LinearLayout> -- -
After you've declared your layout in XML, save the file with the .xml extension,
-in your Android project's res/layout/ directory, so it will properly compile.
We'll discuss each of the attributes shown here a little later.
- -When you compile your application, each XML layout file is compiled into a
-{@link android.view.View} resource. You should load the layout resource from your application code, in your
-{@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} callback implementation.
-Do so by calling {@link android.app.Activity#setContentView(int) setContentView()},
-passing it the reference to your layout resource in the form of:
-R.layout.layout_file_name
-For example, if your XML layout is saved as main_layout.xml, you would load it
-for your Activity like so:
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView.(R.layout.main_layout);
-}
-
-
-The onCreate() callback method in your Activity is called by the Android framework when
-your Activity is launched (see the discussion on Lifecycles, in the
-Application Fundamantals, for more on this).
Every View and ViewGroup object supports their own variety of XML attributes.
-Some attributes are specific to a View object (for example, TextView supports the textSize
-attribute), but these attributes are also inherited by any View objects that may extend this class.
-Some are common to all View objects, because they are inherited from the root View class (like
-the id attribute). And, other attributes are considered "layout parameters," which are
-attributes that describe certain layout orientations of the View object, as defined by that object's
-parent ViewGroup object.
Any View object may have an integer ID associated with it, to uniquely identify the View within the tree.
-When the application is compiled, this ID is referenced as an integer, but the ID is typically
-assigned in the layout XML file as a string, in the id attribute.
-This is an XML attribute common to all View objects
-(defined by the {@link android.view.View} class) and you will use it very often.
-The syntax for an ID, inside an XML tag is:
android:id="@+id/my_button"- -
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest
-of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must
-be created and added to our resources (in the R.java file). There are a number of other ID resources that
-are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol,
-but must add the android package namespace, like so:
android:id="@android:id/empty"-
With the android package namespace in place, we're now referencing an ID from the android.R
-resources class, rather than the local resources class.
In order to create views and reference them from the application, a common pattern is to:
--<Button android:id="@+id/my_button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/my_button_text"/> --
{@link android.app.Activity#onCreate(Bundle) onCreate()} method):
--Button myButton = (Button) findViewById(R.id.my_button); --
Defining IDs for view objects is important when creating a {@link android.widget.RelativeLayout}. -In a relative layout, sibling views can define their layout relative to another sibling view, -which is referenced by the unique ID.
-An ID need not be unique throughout the entire tree, but it should be -unique within the part of the tree you are searching (which may often be the entire tree, so it's best -to be completely unique when possible).
- - -XML layout attributes named layout_something define
-layout parameters for the View that are appropriate for the ViewGroup in which it resides.
Every ViewGroup class implements a nested class that extends {@link -android.view.ViewGroup.LayoutParams}. This subclass -contains property types that define the size and position for each child view, as -appropriate for the view group. As you can see in the figure below, the parent -view group defines layout parameters for each child view (including the child view group).
- -
-
-Note that every LayoutParams subclass has its own syntax for setting -values. Each child element must define LayoutParams that are appropriate for its parent, -though it may also define different LayoutParams for its own children.
- -All view groups include a width and height (layout_width and layout_height),
-and each view is required to define them.
-Many LayoutParams also include optional margins and
-borders. You can specify width and height with exact measurements, though you probably won't want
-to do this often. More often, you will tell your view to size itself either to
-the dimensions required by its content, or to become as big as its parent view group
-will allow (with the wrap_content and fill_parent values, respectively).
-The accepted measurement types are defined in the
-Available Resources document.
- The geometry of a view is that of a rectangle. A view has a location, - expressed as a pair of left and top coordinates, and - two dimensions, expressed as a width and a height. The unit for location - and dimensions is the pixel. -
- -- It is possible to retrieve the location of a view by invoking the methods - {@link android.view.View#getLeft()} and {@link android.view.View#getTop()}. The former returns the left, or X, - coordinate of the rectangle representing the view. The latter returns the - top, or Y, coordinate of the rectangle representing the view. These methods - both return the location of the view relative to its parent. For instance, - when getLeft() returns 20, that means the view is located 20 pixels to the - right of the left edge of its direct parent. -
- -
- In addition, several convenience methods are offered to avoid unnecessary
- computations, namely {@link android.view.View#getRight()} and {@link android.view.View#getBottom()}.
- These methods return the coordinates of the right and bottom edges of the
- rectangle representing the view. For instance, calling {@link android.view.View#getRight()}
- is similar to the following computation: getLeft() + getWidth().
-
- The size of a view is expressed with a width and a height. A view actually - possess two pairs of width and height values. -
- -- The first pair is known as measured width and - measured height. These dimensions define how big a view wants to be - within its parent. The - measured dimensions can be obtained by calling {@link android.view.View#getMeasuredWidth()} - and {@link android.view.View#getMeasuredHeight()}. -
- -- The second pair is simply known as width and height, or - sometimes drawing width and drawing height. These - dimensions define the actual size of the view on screen, at drawing time and - after layout. These values may, but do not have to, be different from the - measured width and height. The width and height can be obtained by calling - {@link android.view.View#getWidth()} and {@link android.view.View#getHeight()}. -
- -- To measure its dimensions, a view takes into account its padding. The padding - is expressed in pixels for the left, top, right and bottom parts of the view. - Padding can be used to offset the content of the view by a specific amount of - pixels. For instance, a left padding of 2 will push the view's content by - 2 pixels to the right of the left edge. Padding can be set using the - {@link android.view.View#setPadding(int, int, int, int)} method and queried by calling - {@link android.view.View#getPaddingLeft()}, {@link android.view.View#getPaddingTop()}, - {@link android.view.View#getPaddingRight()} and {@link android.view.View#getPaddingBottom()}. -
- -- Even though a view can define a padding, it does not provide any support for - margins. However, view groups provide such a support. Refer to - {@link android.view.ViewGroup} and - {@link android.view.ViewGroup.MarginLayoutParams} for further information. -
- -For more information about dimensions, see Dimension Values.
- - - - diff --git a/docs/html/guide/topics/ui/how-android-draws.jd b/docs/html/guide/topics/ui/how-android-draws.jd deleted file mode 100644 index a511005..0000000 --- a/docs/html/guide/topics/ui/how-android-draws.jd +++ /dev/null @@ -1,94 +0,0 @@ -page.title=How Android Draws Views -parent.title=User Interface -parent.link=index.html -@jd:body - - -When an Activity receives focus, it will be requested to draw its layout. -The Android framework will handle the procedure for drawing, but the Activity must provide -the root node of its layout hierarchy.
- -Drawing begins with the root node of the layout. It is requested to measure and
-draw the layout tree. Drawing is handled by walking the tree and rendering each View that
- intersects the invalid region. In turn, each View group is responsible for requesting
-each of its children to be drawn (with the {@link android.view.View#draw(Canvas) draw()} method)
-and each View is responsible for drawing itself.
- Because the tree is traversed in-order,
- this means that parents will be drawn before (i.e., behind) their children, with
- siblings drawn in the order they appear in the tree.
-
The framework will not draw Views that are not in the invalid region, and also - will take care of drawing the Views background for you.
-You can force a View to draw, by calling {@link android.view.View#invalidate()}.
-
- Drawing the layout is a two pass process: a measure pass and a layout pass. The measuring
- pass is implemented in {@link android.view.View#measure(int, int)} and is a top-down traversal
- of the View tree. Each View pushes dimension specifications down the tree
- during the recursion. At the end of the measure pass, every View has stored
- its measurements. The second pass happens in
- {@link android.view.View#layout(int,int,int,int)} and is also top-down. During
- this pass each parent is responsible for positioning all of its children
- using the sizes computed in the measure pass.
-
- When a View's measure() method returns, its {@link android.view.View#getMeasuredWidth()} and
- {@link android.view.View#getMeasuredHeight()} values must be set, along with those for all of
- that View's descendants. A View's measured width and measured height values
- must respect the constraints imposed by the View's parents. This guarantees
- that at the end of the measure pass, all parents accept all of their
- children's measurements. A parent View may call measure() more than once on
- its children. For example, the parent may measure each child once with
- unspecified dimensions to find out how big they want to be, then call
- measure() on them again with actual numbers if the sum of all the children's
- unconstrained sizes is too big or too small (i.e., if the children don't agree among themselves
- as to how much space they each get, the parent will intervene and set the rules on the second pass).
-
- To intiate a layout, call {@link android.view.View#requestLayout}. This method is typically
- called by a View on itself when it believes that is can no longer fit within
- its current bounds.
- The measure pass uses two classes to communicate dimensions. The - {@link android.view.View.MeasureSpec} class is used by Views to tell their parents how they - want to be measured and positioned. The base LayoutParams class just - describes how big the View wants to be for both width and height. For each - dimension, it can specify one of:
-There are subclasses of LayoutParams for different subclasses of ViewGroup. - For example, AbsoluteLayout has its own subclass of LayoutParams which adds - an X and Y value. -
- -- MeasureSpecs are used to push requirements down the tree from parent to - child. A MeasureSpec can be in one of three modes:
-measure() on its child
- with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
- tall the child View wants to be given a width of 240 pixels.In an Android application, the user interface is built using {@link android.view.View} and -{@link android.view.ViewGroup} objects. There are many types of views and view groups, each of which -is a descendant of the {@link android.view.View} class.
- -View objects are the basic units of user interface expression on the Android platform. -The View class serves as the base for subclasses called "widgets," which offer fully implemented -UI objects, like text fields and buttons. The ViewGroup class serves as the base for subclasses called "layouts," -which offer different kinds of layout architecture, like linear, tabular and relative.
- -A View object is a data structure whose properties store the layout parameters and content for a specific -rectangular area of the screen. A View object handles its own measurement, layout, drawing, focus change, -scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides. As an -object in the user interface, a View is also a point of interaction for the user and the receiver -of the interaction events.
- - -On the Android platform, you define an Activity's UI using a hierarchy of View and ViewGroup nodes, -as shown in the diagram below. This hierarchy tree can be as simple or complex as you need it to be, and you -can build it up using Android's set of predefined widgets and layouts, or with custom Views that you -create yourself.
- -
-
-
-In order to attach the view hierarchy tree to the screen for rendering, your Activity must call the
-{@link android.app.Activity#setContentView(int) setContentView()}
-method and pass a reference to the root node object. The Android system
-receives this reference and uses it to invalidate, measure, and draw the tree. The root node of the hierarchy requests
-that its child nodes draw themselves — in turn, each view group node is responsible for calling
-upon each of its own child views to draw themselves.
-The children may request a size and location within the parent, but the parent object has the final
-decision on where how big each child can be. Android parses
-the elements of your layout in-order (from the top of the hierarchy tree), instantiating the Views and
-adding them to their parent(s). Because these are drawn in-order, if there are elements that
-overlap positions, the last one to be drawn will lie on top of others previously drawn to that space.
For a more detailed discussion on how view hierarchies are measured -and drawn, read How Android Draws Views.
- - -The most common way to define your layout and express the view hierarchy is with an XML layout file. -XML offers a human-readable structure for the layout, much like HTML. Each element in XML is -either a View or ViewGroup object (or descendent thereof). View objects are leaves in the tree, -ViewGroup objects are branches in the tree (see the View Hierarchy figure above).
-The name of an XML element
-is respective to the Java class that it represents. So a <TextView> element creates
-a {@link android.widget.TextView} in your UI, and a <LinearLayout> element creates
-a {@link android.widget.LinearLayout} view group. When you load a layout resource,
-the Android system initializes these run-time objects, corresponding to the elements in your layout.
For example, a simple vertical layout with a text view and a button looks like this:
--<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:orientation="vertical" > - <TextView android:id="@+id/text" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Hello, I am a TextView" /> - <Button android:id="@+id/button" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Hello, I am a Button" /> -</LinearLayout> -- -
Notice that the LinearLayout element contains both the TextView and the Button. You can nest -another LinearLayout (or other type of view group) inside here, to lengthen the view hierarchy and create a more -complex layout.
- -For more on building a UI layout, read Declaring Layout. - -
Tip: You can also draw View and ViewGroups objects in Java code,
- using the {@link android.view.ViewGroup#addView(View)} methods
- to dynamically insert new View and ViewGroup objects.
There are a variety of ways in which you can layout your views. Using more and different kinds of view groups, -you can structure child views and view groups in an infinite number of ways. -Some pre-defined view groups offered by Android (called layouts) include LinearLayout, RelativeLayout, AbsoluteLayout, -TableLayout, GridLayout and others. Each offers a unique set of layout parameters that are used to define the -positions of child views and layout structure.
-To learn about some of the different kinds of view groups used for a layout, -read Common Layout Objects.
- - -A widget is a View object that serves as an interface for interaction with the user. -Android provides a set of fully implemented -widgets, like buttons, checkboxes, and text-entry fields, so you can quickly build your UI. -Some widgets provided by Android are more complex, like a date picker, a clock, and zoom controls. -But you're not limited to the kinds of widgets provided by the Android platform. If you'd -like to do something more customized and create your own actionable elements, you can, by defining your own -View object or by extending and combining existing widgets.
-Read more in Building Custom Components.
- -For a list of the widgets provided by Android, see the {@link android.widget} package.
- - -Once you've added some Views/widgets to the UI, you probably want to know about the -user's interaction with them, so you can perform actions. To be informed of UI events, you need to -do one of two things:
-On<something>().
-For example, {@link android.view.View.OnClickListener} (for handling "clicks" on a View),
-{@link android.view.View.OnTouchListener} (for handling touch screen events in a View), and
-{@link android.view.View.OnKeyListener} (for handling device key presses within a View). So if you want your View
-to be notified when it is "clicked" (such as when a button is selected), implement OnClickListener and define
-its onClick() callback method (where you perform the action upon click), and register it
-to the View with {@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()}.
-{@link android.view.View#onTouchEvent(MotionEvent) onTouchEvent()}), when
-the trackball is moved ({@link android.view.View#onTrackballEvent(MotionEvent) onTrackballEvent()}),
-or when a key on the device is pressed ({@link android.view.View#onKeyDown(int, KeyEvent)
-onKeyDown()}). This allows you to define the default behavior for each event inside your custom View and determine
-whether the event should be passed on to some other child View. Again, these are callbacks to the View class,
-so your only chance to define them is when you
-build a custom component.
-Continue reading about handling user interaction with Views in the Handling UI Events -document.
- - -Application menus are another important part of an application's UI. Menus offers a reliable interface that reveals -application functions and settings. The most common application menu is revealed by pressing -the MENU key on the device. However, you can also add Context Menus, which may be revealed when the user presses -and holds down on an item.
- -Menus are also structured using a View hierarchy, but you don't define this structure yourself. Instead,
-you define the {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} or
-{@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo) onCreateContextMenu()}
-callback methods for your Activity and declare the items that you want to include in your menu.
-At the appropriate time, Android will automatically create the necessary View hierarchy for the menu and
-draw each of your menu items in it.
Menus also handle their own events, so there's no need to register event listeners on the items in your menu.
-When an item in your menu is selected, the {@link android.app.Activity#onOptionsItemSelected(MenuItem)
-onOptionsItemSelected()} or
-{@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}
-method will be called by the framework.
And just like your application layout, you have the option to declare the items for you menu in an XML file.
- -Read Creating Menus to learn more.
- - -Once you've grappled the fundamentals of creating a user interface, you can explore -some advanced features for creating a more complex application interface.
- -Sometimes you'll want to populate a view group with some information that can't be hard-coded, instead, -you want to bind your view to an external source of data. To do this, you use an AdapterView as -your view group and each child View is initialized and populated with data from the Adapter.
-The AdapterView object is an implementation of ViewGroup that determines its child views -based on a given Adapter object. The Adapter acts like a courier between your data source (perhaps an -array of external strings) and the AdapterView, which displays it. There are several implementations -of the Adapter class, for specific tasks, such as the CursorAdapter for reading database data from a Cursor, -or an ArrayAdapter for reading from an arbitrary array.
-To learn more about using an Adapter to populate your views, read -Binding to Data with AdapterView.
- - -Perhaps you're not satisfied with the look of the standard widgets. To revise them, you can create some -of your own styles and themes.
- -Styles and themes are resources. Android provides some default style and theme resources that you can use, -or you can declare your own custom style and theme resources.
-Learn more about using styles and themes in the -Applying Styles and Themes document.
diff --git a/docs/html/guide/topics/ui/layout-objects.jd b/docs/html/guide/topics/ui/layout-objects.jd deleted file mode 100644 index cf85fd6..0000000 --- a/docs/html/guide/topics/ui/layout-objects.jd +++ /dev/null @@ -1,305 +0,0 @@ -page.title=Common Layout Objects -parent.title=User Interface -parent.link=index.html -@jd:body - -This section describes some of the more common types of layout objects -to use in your applications. Like all layouts, they are subclasses of {@link android.view.ViewGroup ViewGroup}.
- -Also see the Hello Views tutorials for -some guidance on using more Android View layouts.
- -{@link android.widget.FrameLayout FrameLayout} is the simplest type of layout -object. It's basically a blank space on your screen that you can -later fill with a single object — for example, a picture that you'll swap in and out. -All child elements of the FrameLayout are pinned to the top left corner of the screen; you cannot -specify a different location for a child view. Subsequent child views will simply be drawn over previous ones, -partially or totally obscuring them (unless the newer object is transparent). -
- - -{@link android.widget.LinearLayout LinearLayout} aligns all children in a
-single direction — vertically or horizontally, depending on how you
-define the orientation attribute. All children are
-stacked one after the other, so a vertical list will only have one child per
-row, no matter how wide they are, and a horizontal list will only be one row
-high (the height of the tallest child, plus padding). A {@link
-android.widget.LinearLayout LinearLayout} respects margins between children
-and the gravity (right, center, or left alignment) of each child.
{@link android.widget.LinearLayout LinearLayout} also supports assigning a -weight to individual children. This attribute assigns an "importance" value to a view, -and allows it to expand to fill any remaining space in the parent view. -Child views can specify an integer weight value, and then any remaining space in the view group is -assigned to children in the proportion of their declared weight. Default -weight is zero. For example, if there are three text boxes and two of -them declare a weight of 1, while the other is given no weight (0), the third text box without weight -will not grow and will only occupy the area required by its content. -The other two will expand equally to fill the space remaining after all three boxes are measured. -If the third box is then given a weight of 2 (instead of 0), then it is now declared -"more important" than both the others, so it gets half the total remaining space, while the first two -share the rest equally.
- -Tip: To create a proportionate size
-layout on the screen, create a container view group object with the
-layout_width and layout_height attributes set to fill_parent; assign
-the children height or width to 0 (zero); then assign relative
-weight values
-to each child, depending on what proportion of the screen each should
-have.
The following two forms represent a {@link android.widget.LinearLayout LinearLayout} with a set of elements: a -button, some labels and text boxes. The text boxes have their width set to fill_parent; other -elements are set to wrap_content. The gravity, by default, is left. -The difference between the two versions of the form is that the form -on the left has weight values unset (0 by default), while the form on the right has -the comments text box weight set to 1. If the Name textbox had also been set -to 1, the Name and Comments text boxes would be the same height.
- -
-
-Within a horizontal {@link android.widget.LinearLayout LinearLayout}, items are aligned by the position of
-their text base line (the first line of the first list element — topmost or
-leftmost — is considered the reference line). This is so that people scanning
-elements in a form shouldn't have to jump up and down to read element text in
-neighboring elements. This can be turned off by setting
-android:baselineAligned="false" in the layout XML.
To view other sample code, see the -Hello LinearLayout tutorial.
- - -{@link android.widget.TableLayout} positions its children into rows - and columns. TableLayout containers do not display border lines for their rows, columns, - or cells. The table will have as many columns as the row with the most cells. A table can leave -cells empty, but cells cannot span columns, as they can in HTML.
-{@link android.widget.TableRow} objects are the child views of a TableLayout -(each TableRow defines a single row in the table). -Each row has zero or more cells, each of which is defined by any kind of other View. So, the cells of a row may be -composed of a variety of View objects, like ImageView or TextView objects. -A cell may also be a ViewGroup object (for example, you can nest another TableLayout as a cell).
-The following sample layout has two rows and two cells in each. The accompanying screenshot shows the -result, with cell borders displayed as dotted lines (added for visual effect).
- -
- -<?xml version="1.0" encoding="utf-8"?> -<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:stretchColumns="1"> - <TableRow> - <TextView - android:text="@string/table_layout_4_open" - android:padding="3dip" /> - <TextView - android:text="@string/table_layout_4_open_shortcut" - android:gravity="right" - android:padding="3dip" /> - </TableRow> - - <TableRow> - <TextView - android:text="@string/table_layout_4_save" - android:padding="3dip" /> - <TextView - android:text="@string/table_layout_4_save_shortcut" - android:gravity="right" - android:padding="3dip" /> - </TableRow> -</TableLayout> - |
- ![]() |
-
Columns can be hidden, marked to stretch and fill the available screen space, - or can be marked as shrinkable to force the column to shrink until the table - fits the screen. See the {@link android.widget.TableLayout TableLayout reference} -documentation for more details.
- -To view sample code, see the Hello -TableLayout tutorial.
- - -{@link android.widget.AbsoluteLayout} enables child views to specify - their own exact x/y coordinates on the screen. Coordinates (0,0) is the upper left - corner, and values increase as you move down and to the right. Margins are not - supported, and overlapping elements are allowed (although not recommended). We - generally recommend against using AbsoluteLayout unless you have good reasons - to use it, because it is fairly rigid and does not adjust to different types of - displays.
- - -{@link android.widget.RelativeLayout} lets child views specify their - position relative to the parent view or to each other (specified by ID). So you can - align two elements by right border, or make one below another, centered in - the screen, centered left, and so on. Elements are rendered in the order given, so if the first element - is centered in the screen, other elements aligning themselves to that element - will be aligned relative to screen center. Also, because of this ordering, if using XML to specify this layout, - the element that you will reference (in order to position other view objects) must be listed in the XML -file before you refer to it from the other views via its reference ID.
-The example below shows an XML file and the resulting screen in the UI. -Note that the attributes that refer to relative elements (e.g., layout_toLeft) -refer to the ID using the syntax of a relative resource -(@id/id).
- -
- -<?xml version="1.0" encoding="utf-8"?> -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:background="@drawable/blue" - android:padding="10px" > - - <TextView android:id="@+id/label" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:text="Type here:" /> - - <EditText android:id="@+id/entry" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:background="@android:drawable/editbox_background" - android:layout_below="@id/label" /> - - <Button android:id="@+id/ok" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_below="@id/entry" - android:layout_alignParentRight="true" - android:layout_marginLeft="10px" - android:text="OK" /> - - <Button android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_toLeftOf="@id/ok" - android:layout_alignTop="@id/ok" - android:text="Cancel" /> -</RelativeLayout> - |
- ![]() |
-
Some of these properties are supported directly by
- the element, and some are supported by its LayoutParams member (subclass RelativeLayout
- for all the elements in this screen, because all elements are children of a RelativeLayout
- parent object). The defined RelativeLayout parameters are: width, height,
- below, alignTop, toLeft, padding[Bottom|Left|Right|Top],
- and margin[Bottom|Left|Right|Top]. Note that some of these parameters specifically support
- relative layout positions — their values must be the ID of the element to which you'd like this view laid relative.
- For example, assigning the parameter toLeft="my_button" to a TextView would place the TextView to
- the left of the View with the ID my_button (which must be written in the XML before the TextView).
To view this sample code, see the Hello -RelativeLayout tutorial.
- - -These objects all hold child UI elements. Some provide their own form of a visible UI, while others - are invisible structures that only manage the layout of their child views.
-| Class | -Description | -
|---|---|
| {@link android.widget.AbsoluteLayout AbsoluteLayout} |
- Enables you to specify the location of child objects relative to the - parent in exact measurements (for example, pixels). | -
| {@link android.widget.FrameLayout FrameLayout} | -Layout that acts as a view frame to display - a single object. | -
| {@link android.widget.Gallery Gallery} | -A horizontal scrolling display of images, from a bound list. | -
| {@link android.widget.GridView GridView} | -Displays a scrolling grid of m columns and n rows. | -
| {@link android.widget.LinearLayout LinearLayout} | -A layout that organizes its children into a single horizontal or vertical - row. It creates a scrollbar if the length of the window exceeds the length - of the screen. | -
| {@link android.widget.ListView ListView} | -Displays a scrolling single column list. | -
| {@link android.widget.RelativeLayout RelativeLayout} | -Enables you to specify the location of child objects relative to each - other (child A to the left of child B) or to the parent (aligned to the - top of the parent). | -
| {@link android.widget.ScrollView ScrollView} | -A vertically scrolling column of elements. | -
| {@link android.widget.Spinner Spinner} | -Displays a single item at a time from a bound list, inside a one-row - textbox. Rather like a one-row listbox that can scroll either horizontally - or vertically. | -
| {@link android.view.SurfaceView SurfaceView} | -Provides direct access to a dedicated drawing surface. It can hold child - views layered on top of the surface, but is intended for applications - that need to draw pixels, rather than using widgets. | -
| {@link android.widget.TabHost TabHost} | -Provides a tab selection list that monitors clicks and enables the application - to change the screen whenever a tab is clicked. | -
| {@link android.widget.TableLayout TableLayout} | -A tabular layout with an arbitrary number of rows and columns, each cell - holding the widget of your choice. The rows resize to fit the largest - column. The cell borders are not - visible. | -
| {@link android.widget.ViewFlipper ViewFlipper} | -A list that displays one item at a time, inside a one-row textbox. It - can be set to swap items at timed intervals, like a slide show. | -
| {@link android.widget.ViewSwitcher ViewSwitcher} | -Same as ViewFlipper. | -
Menus are an important part of any application. They provide familiar interfaces -that reveal application functions and settings. Android offers an easy programming interface -for developers to provide standardized application menus for various situations.
- -Android offers three fundamental types of application menus:
-
-The Options Menu is opened by pressing the device MENU key. -When opened, the Icon Menu is displayed, which holds the first six menu items. -If more than six items are added to the Options Menu, then those that can't fit -in the Icon Menu are revealed in the Expanded Menu, via the "More" menu item. The Expanded Menu -is automatically added when there are more than six items.
- -The Options Menu is where you should include basic application functions -and any necessary navigation items (e.g., to a home screen or application settings). -You can also add Submenus for organizing topics -and including extra menu functionality.
- -When this menu is opened for the first time,
-the Android system will call the Activity {@link android.app.Activity#onCreateOptionsMenu(Menu)
-onCreateOptionsMenu()} callback method. Override this method in your Activity
-and populate the {@link android.view.Menu} object given to you. You can populate the menu by
-inflating a menu resource that was defined in XML, or by calling
-{@link android.view.Menu#add(CharSequence) add()}
-for each item you'd like in the menu. This method adds a {@link android.view.MenuItem}, and returns the
-newly created object to you. You can use the returned MenuItem to set additional properties like
-an icon, a keyboard shortcut, an intent, and other settings for the item.
There are multiple {@link android.view.Menu#add(CharSequence) add()} methods.
-Usually, you'll want to use one that accepts an itemId argument.
-This is a unique integer that allows you to identify the item during a callback.
When a menu item is selected from the Options Menu, you will recieve a callback to the
-{@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}
-method of your Activity. This callback passes you the
-MenuItem that has been selected. You can identify the item by requesting the
-itemId, with {@link android.view.MenuItem#getItemId() getItemId()},
-which returns the integer that was assigned with the add() method. Once you identify
-the menu item, you can take the appropriate action.
Here's an example of this procedure, inside an Activity, wherein we create an -Options Menu and handle item selections:
- -
-/* Creates the menu items */
-public boolean onCreateOptionsMenu(Menu menu) {
- menu.add(0, MENU_NEW_GAME, 0, "New Game");
- menu.add(0, MENU_QUIT, 0, "Quit");
- return true;
-}
-
-/* Handles item selections */
-public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case MENU_NEW_GAME:
- newGame();
- return true;
- case MENU_QUIT:
- quit();
- return true;
- }
- return false;
-}
-
-
-The add() method used in this sample takes four arguments:
-groupId, itemId, order, and title.
-The groupId allows you to associate this menu item with a group of other items
-(more about Menu groups, below) — in
-this example, we ignore it. itemId is a unique integer that we give the
-MenuItem so that can identify it in the next callback. order allows us to
-define the display order of the item — by default, they are displayed by the
-order in which we add them. title is, of course, the name that goes on the
-menu item (this can also be a
-string resource,
-and we recommend you do it that way for easier localization).
Tip: -If you have several menu items that can be grouped together with a title, -consider organizing them into a Submenu.
- -Icons can also be added to items that appears in the Icon Menu with
-{@link android.view.MenuItem#setIcon(Drawable) setIcon()}. For example:
-menu.add(0, MENU_QUIT, 0, "Quit") - .setIcon(R.drawable.menu_quit_icon);- -
If you want to sometimes re-write the Options Menu as it is opened, override the
-{@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method, which is
-called each time the menu is opened. This will pass you the Menu object, just like the
-onCreateOptionsMenu() callback. This is useful if you'd like to add or remove
-menu options depending on the current state of an application or game.
Note: -When changing items in the menu, it's bad practice to do so based on the currently selected item. -Keep in mind that, when in touch mode, there will not be a selected (or focused) item. Instead, you -should use a Context Menu for such behaviors, when you want to provide -functionality based on a particular item in the UI.
- - -The Android context menu is similar, in concept, to the menu revealed with a "right-click" on a PC. -When a view is registered to a context menu, -performing a "long-press" (press and hold for about two seconds) on the object -will reveal a floating menu that provides functions relating to that item. -Context menus can be registered to any View object, -however, they are most often used for items in a -{@link android.widget.ListView}, which helpfully indicates the presence of the context menu -by transforming the background color of the ListView item when pressed. -(The items in the phone's contact list offer an example of this feature.) -
- -Note: Context menu items do not support icons or shortcut keys.
- -To create a context menu, you must override the Activity's context menu callback methods:
-{@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo) onCreateContextMenu()} and
-{@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}.
-Inside the onCreateContextMenu() callback method, you can add menu items using one of the
-{@link android.view.Menu#add(CharSequence) add()} methods, or by
-inflating a menu resource that was defined in XML.
-Then, register a {@link android.view.ContextMenu} for the View, with
-{@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()}.
For example, here is some code that can be used with the -Notepad application -to add a context menu for each note in the list:
-
-public void onCreateContextMenu(ContextMenu menu, View v,
- ContextMenuInfo menuInfo) {
- super.onCreateContextMenu(menu, v, menuInfo);
- menu.add(0, EDIT_ID, 0, "Edit");
- menu.add(0, DELETE_ID, 0, "Delete");
-}
-
-public boolean onContextItemSelected(MenuItem item) {
- AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
- switch (item.getItemId()) {
- case EDIT_ID:
- editNote(info.id);
- return true;
- case DELETE_ID:
- deleteNote(info.id);
- return true;
- default:
- return super.onContextItemSelected(item);
- }
-}
-
-
-In onCreateContextMenu(), we are given not only the ContextMenu to
-which we will add {@link android.view.MenuItem}s, but also the {@link android.view.View}
-that was selected and a {@link android.view.ContextMenu.ContextMenuInfo ContextMenuInfo} object,
-which provides additional information about the object that was selected.
-In this example, nothing special is done in onCreateContextMenu() — just
-a couple items are added as usual. In the onContextItemSelected()
-callback, we request the {@link android.widget.AdapterView.AdapterContextMenuInfo AdapterContextMenuInfo}
-from the {@code MenuItem}, which provides information about the currently selected item.
-All we need from
-this is the list ID for the selected item, so whether editing a note or deleting it,
-we find the ID with the {@code AdapterContextMenuInfo.info} field of the object. This ID
-is passed to the editNote() and deleteNote() methods to perfrom
-the respective action.
Now, to register this context menu for all the items in a {@link android.widget.ListView},
-we pass the entire {@code ListView} to the
-{@link android.app.Activity#registerForContextMenu(View)} method:
registerForContextMenu(getListView());-
Remember, you can pass any View object to register a context menu. Here,
-{@link android.app.ListActivity#getListView()} returns the ListView
-object used in the Notepad application's {@link android.app.ListActivity}. As such, each item
-in the list is registered to this context menu.
A sub menu can be added within any menu, except another sub menu. -These are very useful when your application has a lot of functions that may be -organized in topics, like the items in a PC application's menu bar (File, Edit, View, etc.).
- -A sub menu is created by adding it to an existing {@link android.view.Menu}
-with {@link android.view.Menu#addSubMenu(CharSequence) addSubMenu()}.
-This returns a {@link android.view.SubMenu} object (an extension of {@link android.view.Menu}).
-You can then add additional items to this menu, with the normal routine, using
-the {@link android.view.Menu#add(CharSequence) add()} methods. For example:
-public boolean onCreateOptionsMenu(Menu menu) {
- boolean result = super.onCreateOptionsMenu(menu);
-
- SubMenu fileMenu = menu.addSubMenu("File");
- SubMenu editMenu = menu.addSubMenu("Edit");
- fileMenu.add("new");
- fileMenu.add("open");
- fileMenu.add("save");
- editMenu.add("undo");
- editMenu.add("redo");
-
- return result;
-}
-
-Callbacks for items selected in a sub menu are made to the parent menu's callback method.
-For the example above, selections in the sub menu will be handled by the
-onOptionsItemSelected() callback.
You can also add Submenus when you define the parent menu in XML.
- - -Just like Android UI layouts, you can define application menus in XML, then inflate them
-in your menu's onCreate...() callback method. This makes your application code cleaner and
-separates more interface design into XML, which is easier to visualize.
To start, create a new folder in your project res/ directory called menu.
-This is where you should keep all XML files that define your application menus.
In a menu XML layout, there are
-three valid elements: <menu>, <group> and <item>. The
-item and group elements must be children of a menu, but item
-elements may also be the children of a group, and another menu element may be the child
-of an item (to create a Submenu). Of course, the root node of any file
-must be a menu element.
As an example, we'll define the same menu created in the Options Menu section,
-above. We start with an XML file named options_menu.xml inside the res/menu/ folder:
-<menu xmlns:android="http://schemas.android.com/apk/res/android"> - <item android:id="@+id/new_game" - android:title="New Game" /> - <item android:id="@+id/quit" - android:title="Quit" /> -</menu> -- -
Then, in the onCreateOptionsMenu() method, we inflate this resource using
-{@link android.view.MenuInflater#inflate(int,Menu) MenuInflater.inflate()}:
-public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.options_menu, menu);
- return true;
-}
-
-
-The {@link android.app.Activity#getMenuInflater()} method returns the {@link android.view.MenuInflater}
-for our activity's context. We then call {@link android.view.MenuInflater#inflate(int,Menu) inflate()},
-passing it a pointer to our menu resource and the Menu object given by the callback.
While this small sample may seem like more effort, compared to creating the menu items in the
-onCreateOptionsMenu() method, this will save a lot of trouble when dealing with more items
-and it keeps your application code clean.
You can define menu groups by wrapping item elements in a group
-element, and create Submenus by nesting another menu inside an item.
-Each element also supports all the necessary attributes to control features like shortcut keys,
-checkboxes, icons, and more. To learn about these attributes and more about the XML syntax, see the Menus
-topic in the Available
-Resource Types document.
Here are some other features that can be applied to most menu items.
- -When adding new items to a menu, you can optionally include each item in a group. -A menu group is a collection of menu items that can share certain traits, like -whether they are visible, enabled, or checkable.
- -A group is defined by an integer (or a resource id, in XML). A menu item is added to the group when it is
-added to the menu, using one of the add() methods that accepts a groupId
-as an argument, such as {@link android.view.Menu#add(int,int,int,int)}.
You can show or hide the entire group with
-{@link android.view.Menu#setGroupVisible(int,boolean) setGroupVisible()};
-enable or disable the group with
-{@link android.view.Menu#setGroupEnabled(int,boolean) setGroupEnabled()};
-and set whether the items can be checkable with
-{@link android.view.Menu#setGroupCheckable(int,boolean,boolean) setGroupCheckable()}.
-
-Any menu item can be used as an interface for turning options on and off. This can -be indicated with a checkbox for stand-alone options, or radio buttons for groups of -mutually exlusive options (see the screenshot, to the right).
- -Note: Menu items in the Icon Menu cannot -display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, -then you must personally indicate the state by swapping the icon and/or text -each time the state changes between on and off.
- -To make a single item checkable, use the {@link android.view.MenuItem#setCheckable(boolean)
-setCheckable()} method, like so:
-menu.add(0, VIBRATE_SETTING_ID, 0, "Vibrate") - .setCheckable(true); --
This will display a checkbox with the menu item (unless it's in the Icon Menu). When the item
-is selected, the onOptionsItemSelected() callback is called as usual. It is here that
-you must set the state of the checkbox. You can query the current state of the item with
-{@link android.view.MenuItem#isChecked()} and set the checked state with
-{@link android.view.MenuItem#setChecked(boolean) setChecked()}.
-Here's what this looks like inside the
-onOptionsItemSelected() callback:
-switch (item.getItemId()) {
-case VIBRATE_SETTING_ID:
- if (item.isChecked()) item.setChecked(false);
- else item.setChecked(true);
- return true;
-...
-}
-
-
-To make a group of mutually exclusive radio button items, simply
-assign the same group ID to each menu item
-and call {@link android.view.Menu#setGroupCheckable(int,boolean,boolean)
-setGroupCheckable()}. In this case, you don't need to call setCheckable()
-on each menu items, because the group as a whole is set checkable. Here's an example of
-two mutually exclusive options in a Submenu:
-SubMenu subMenu = menu.addSubMenu("Color");
-subMenu.add(COLOR_MENU_GROUP, COLOR_RED_ID, 0, "Red");
-subMenu.add(COLOR_MENU_GROUP, COLOR_BLUE_ID, 0, "Blue");
-subMenu.setGroupCheckable(COLOR_MENU_GROUP, true, true);
-
-In the setGroupCheckable() method, the first argument is the group ID
-that we want to set checkable. The second argument is whether we want the group items
-to be checkable. The last one is whether we want each item to be exclusively checkable
-(if we set this false, then all the items will be checkboxes instead of radio buttons).
-When the group is set to be exclusive (radio buttons), each time a new item is selected,
-all other are automatically de-selected.
- -
Note: -Checkable menu items are intended to be used only on a per-session basis and not saved to the device -(e.g., the Map mode setting in the Maps application is not saved — screenshot above). -If there are application settings that you would like to save for the user, -then you should store the data using Preferences, -and manage them with a {@link android.preference.PreferenceActivity}.
- - -Quick access shortcut keys using letters and/or numbers can be added to menu items with
-setAlphabeticShortcut(char) (to set char shortcut), setNumericShortcut(int)
-(to set numeric shortcut),
-or setShortcut(char,int) (to set both). Case is not sensitive.
-
-For example:
-menu.add(0, MENU_QUIT, 0, "Quit")
- .setAlphabeticShortcut('q');
-
-Now, when the menu is open (or while holding the MENU key), pressing the "q" key will -select this item.
-This shortcut key will be displayed as a tip in the menu item, below the menu item name -(except for items in the Icon Menu).
-Note: Shortcuts cannot be added to items in a Context Menu.
- - -If you've read the Application -Fundamentals, then you're at least a little familiar -with Android Intents. These allow applications to bind with each other, share information, -and perform user tasks cooperatively. Just like your application might fire an Intent to launch a web browser, -an email client, or another Activity in your application, -you can perform such actions from within a menu. -There are two ways to do this: define an Intent and assign it to a single menu item, or -define an Intent and allow Android to search the device for activities and dynamically add a -menu item for each one that meets the Intent criteria.
- -For more information on creating Intents and providing your application's services to other applications, -read the Intents -and Intent Filters document.
- -If you want to offer a specific menu item that launches a new Activity, then you
-can specifically define an Intent for the menu item with the
-{@link android.view.MenuItem#setIntent(Intent)
-setIntent()} method.
For example, inside the {@link android.app.Activity#onCreateOptionsMenu(Menu)
-onCreateOptionsMenu()} method, you can define a new menu item with an Intent like this:
-MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID, 0, "Select Photo"); -menuItem.setIntent(new Intent(this, PhotoPicker.class)); --
Android will automatically launch the Activity when the item is selected.
- -Note: This will not return a result to your Activity.
-If you wish to be returned a result, then do not use setIntent().
-Instead, handle the selection as usual in the onOptionsMenuItemSelected()
-or onContextMenuItemSelected() callback and call
-{@link android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()}.
-
If there are potentially multiple activities that are relevant to your current -Activity or selected item, then the application can dynamically add menu items that execute other -services.
-During menu creation, define an Intent with the category Intent.ALTERNATIVE_CATEGORY and/or
-Intent.SELECTED_ALTERNATIVE, the MIME type currently selected (if any), and any other
-requirements, the same way as you would satisfy an intent filter to open a new
-Activity. Then call
-{@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
-addIntentOptions()} to have Android search for any services meeting those requirements
-and add them to the menu for you. If there are no applications installed
-that satisfy the Intent, then no additional menu items are added.
Note:
-SELECTED_ALTERNATIVE is used to handle the currently selected element on the
-screen. So, it should only be used when creating a Menu in onCreateContextMenu() or
-onPrepareOptionsMenu(), which is called every time the Options Menu is opened.
Here's an example demonstrating how an application would search for -additional services to display on its menu.
- -
-public boolean onCreateOptionsMenu(Menu menu){
- super.onCreateOptionsMenu(menu);
-
- // Create an Intent that describes the requirements to fulfill, to be included
- // in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE.
- Intent intent = new Intent(null, getIntent().getData());
- intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
-
- // Search for, and populate the menu with, acceptable offering applications.
- menu.addIntentOptions(
- thisClass.INTENT_OPTIONS, // Menu group
- 0, // Unique item ID (none)
- 0, // Order for the items (none)
- this.getComponentName(), // The current Activity name
- null, // Specific items to place first (none)
- intent, // Intent created above that describes our requirements
- 0, // Additional flags to control items (none)
- null); // Array of MenuItems that corrolate to specific items (none)
-
- return true;
-}
-
-For each Activity found that provides an Intent Filter matching the Intent defined, a menu
-item will be added, using the android:label value of the intent filter as the text
-for the menu item.
-The {@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[]) addIntentOptions()} method will also return the number of menu items added.
Also be aware that, when addIntentOptions() is called, it will override any and all
-menu items in the menu group specified in the first argument.
If you wish to offer the services of your Activity to other application menus, then you
-only need to define an intent filter as usual. Just be sure to include the ALTERNATIVE and/or
-SELECTED_ALTERNATIVE values in the name attribute of
-a <category> element in the intent filter. For example:
-<intent-filter label="Resize Image"> - ... - <category android:name="android.intent.category.ALTERNATIVE" /> - <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> - ... -</intent-filter> --
read more about writing intent filters in the -Intents and Intent Filters document.
- -For a sample application using this technique, see the -Note Pad -sample code.
diff --git a/docs/html/guide/topics/ui/themes.jd b/docs/html/guide/topics/ui/themes.jd deleted file mode 100644 index 956ffe1..0000000 --- a/docs/html/guide/topics/ui/themes.jd +++ /dev/null @@ -1,182 +0,0 @@ -page.title=Applying Styles and Themes -parent.title=User Interface -parent.link=index.html -@jd:body - - - -When designing your application, you can use styles and themes to apply uniform formatting to its various screens and UI elements. - -
Styles and themes are resources. Android provides some default style and theme resources that you can use, or you can declare your own custom style and theme resources.
- -To create custom styles and themes:
-styles.xml in the your application's res/values directory. Add a root <resources> node.<style> element with a unique name and, optionally, a parent attribute.
- The name is used for referencing these styles later, and the parent indicates what style resource to inherit from.style element, declare format values in one or more <item> element.
- Each item identifies its style property with a name attribute and defines its style value inside the element.Here's an example declaration of a style:
- --<?xml version="1.0" encoding="utf-8"?> -<resources> - <style name="SpecialText" parent="@style/Text"> - <item name="android:textSize">18sp</item> - <item name="android:textColor">#008</item> - </style> -</resources> -- -
As shown, you can use <item> elements to set specific formatting values for the style.
-The name attribute in the item can refer to a standard string, a hex color value,
-or a reference to any other resource type.
Note the parent attribute in the style element. This attribute lets you specify a resource from which the current style will inherit values. The style can inherit from any type of resource that contains the style(s) you want. In general, your styles should always inherit (directly or indirectly) from a standard Android style resource. This way, you only have to define the values that you want to change.
Here's how you would reference the custom style from an XML layout, in this case, for an EditText element:
- --<EditText id="@+id/text1" - style="@style/SpecialText" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:text="Hello, World!" /> -- -
Now this EditText widget will be styled as defined by the style example above.
Just like styles, themes are also declared in XML <style> elements, and are referenced in the same manner.
-The difference is that you can add a theme style only to <application> and <activity> elements —
-they cannot be applied to individual views in the layout.
Here's an example declaration of a theme:
- --<?xml version="1.0" encoding="utf-8"?> -<resources> - <style name="CustomTheme"> - <item name="android:windowNoTitle">true</item> - <item name="windowFrame">@drawable/screen_frame</item> - <item name="windowBackground">@drawable/screen_background_white</item> - <item name="panelForegroundColor">#FF000000</item> - <item name="panelBackgroundColor">#FFFFFFFF</item> - <item name="panelTextColor">?panelForegroundColor</item> - <item name="panelTextSize">14</item> - <item name="menuItemTextColor">?panelTextColor</item> - <item name="menuItemTextSize">?panelTextSize</item> - </style> -</resources> -- -
Notice the use of the at-symbol (@) and the question-mark (?) to reference resources.
-The at-symbol indicates that we're referencing a resource previously defined elsewhere (which may be from
-this project or from the Android framework).
-The question-mark indicates that we're referencing a resource value in the currently loaded theme. This
-is done by referring to a specific <item> by its name value. (E.g.,
-panelTextColor uses the same color assigned to panelForegroundColor, defined beforehand.)
-This technique can be used only in XML resources.
-
To set this theme for all the activites of your application, open the AndroidManifest.xml file and
-edit the <application> tag to include the android:theme attribute with the
-theme name:
-<application android:theme="@style/CustomTheme"> -- -
If you want the theme applied to just one Activity in your application, then add the theme
-attribute to the <activity> tag, instead.
Just as Android provides other built-in resources, there are several themes that you swap in -without having to write one yourself. For example, you can use the Dialog theme to make your Activity -appear like a dialog box. In the manifest, reference an Android theme like so:
- --<activity android:theme="@android:style/Theme.Dialog"> -- -
If you like a theme, but want to slightly tweak it, just add the theme as the parent of your custom theme.
-For example, we'll modify the Theme.Dialog theme. First, we need to import the parent of the
-Dialog theme: Theme. At the top of the resources, add:
-<style name="Theme" parent="@android:Theme"> - <!-- no modification --> -</style> --
Now create a a new theme with Theme.Dialog as the parent:
-<style name="CustomDialogTheme" parent="@android:style/Theme.Dialog"> --
There it is. We've inherited the Dialog theme, so we can adjust its styles as we like. -So, for each item in the Dialog theme that we want to override, we re-define the value under this style and -then use CustomDialogTheme instead of the Theme.Dialog.
- -You can also load a theme for an Activity programmatically, if needed. -To do so, use the {@link android.app.Activity#setTheme(int) setTheme()} -method. Note that, when doing so, you must be sure to set the theme before -instantiating any Views in the context, for example, before calling -setContentView(View) or inflate(int, ViewGroup). This ensures that -the system applies the same theme for all of your UI screens. Here's an example:
- -
- protected void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- ...
- setTheme(android.R.style.Theme_Light);
- setContentView(R.layout.linear_layout_3);
-}
-
-
-If you are considering loading a theme programmatically for the main -screen of your application, note that the theme would not be applied -in any animations the system would use to show the activity, which -would take place before your application starts. In most cases, if -you want to apply a theme to your main screen, doing so in XML - is a better approach.
- -For detailed information about custom styles and themes and referencing them from your application, see -Style -and Theme Resources.
- -For information about default themes and styles available, see {@link android.R.style}.
- - - - - - diff --git a/docs/html/guide/topics/ui/ui-events.jd b/docs/html/guide/topics/ui/ui-events.jd deleted file mode 100644 index f4d114a..0000000 --- a/docs/html/guide/topics/ui/ui-events.jd +++ /dev/null @@ -1,283 +0,0 @@ -page.title=Handling UI Events -parent.title=User Interface -parent.link=index.html -@jd:body - -On Android, there's more than one way to intercept the events from a user's interaction with your application. -When considering events within your user interface, the approach is to capture the events from -the specific View object that the user interacts with. The View class provides the means to do so.
- -Within the various View classes that you'll use to compose your layout, you may notice several public callback
-methods that look useful for UI events. These methods are called by the Android framework when the
-respective action occurs on that object. For instance, when a View (such as a Button) is touched,
-the onTouchEvent() method is called on that object. However, in order to intercept this, you must extend
-the class and override the method. Obviously, extending every View object
-you want to use (just to handle an event) would be obsurd. This is why the View class also contains
-a collection of nested interfaces with callbacks that you can much more easily define. These interfaces,
-called event listeners, are your ticket to capturing the user interaction with your UI.
While you will more commonly use the event listeners to listen for user interaction, there may -come a time when you do want to extend a View class, in order to build a custom component. -Perhaps you want to extend the {@link android.widget.Button} -class to make something more fancy. In this case, you'll be able to define the default event behaviors for your -class using the class event handlers.
- - -An event listener is an interface in the {@link android.view.View} class that contains a single -callback method. These methods will be called by the Android framework when the View to which the listener has -been registered is triggered by user interaction with the item in the UI.
- -Included in the event listener interfaces are the following callback methods:
- -onClick()onLongClick()onFocusChange()onKey()onTouch()onCreateContextMenu()These methods are the sole inhabitants of their respective interface. To define one of these methods
-and handle your events, implement the nested interface in your Activity or define it as an anonymous class.
-Then, pass an instance of your implementation
-to the respective View.set...Listener() method. (E.g., call
-{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()}
-and pass it your implementation of the {@link android.view.View.OnClickListener OnClickListener}.)
The example below shows how to register an on-click listener for a Button.
- -
-// Create an anonymous implementation of OnClickListener
-private OnClickListener mCorkyListener = new OnClickListener() {
- public void onClick(View v) {
- // do something when the button is clicked
- }
-};
-
-protected void onCreate(Bundle savedValues) {
- ...
- // Capture our button from layout
- Button button = (Button)findViewById(R.id.corky);
- // Register the onClick listener with the implementation above
- button.setOnClickListener(mCorkyListener);
- ...
-}
-
-
-You may also find it more conventient to implement OnClickListener as a part of your Activity. -This will avoid the extra class load and object allocation. For example:
-
-public class ExampleActivity extends Activity implements OnClickListener {
- protected void onCreate(Bundle savedValues) {
- ...
- Button button = (Button)findViewById(R.id.corky);
- button.setOnClickListener(this);
- }
-
- // Implement the OnClickListener callback
- public void onClick(View v) {
- // do something when the button is clicked
- }
- ...
-}
-
-
-Notice that the onClick() callback in the above example has
-no return value, but some other event listener methods must return a boolean. The reason
-depends on the event. For the few that do, here's why:
{@link android.view.View.OnLongClickListener#onLongClick(View) onLongClick()} -
- This returns a boolean to indicate whether you have consumed the event and it should not be carried further.
- That is, return true to indicate that you have handled the event and it should stop here;
- return false if you have not handled it and/or the event should continue to any other
- on-click listeners.{@link android.view.View.OnKeyListener#onKey(View,int,KeyEvent) onKey()} -
- This returns a boolean to indicate whether you have consumed the event and it should not be carried further.
- That is, return true to indicate that you have handled the event and it should stop here;
- return false if you have not handled it and/or the event should continue to any other
- on-key listeners.{@link android.view.View.OnTouchListener#onTouch(View,MotionEvent) onTouch()} -
- This returns a boolean to indicate whether your listener consumes this event. The important thing is that
- this event can have multiple actions that follow each other. So, if you return false when the
- down action event is received, you indicate that you have not consumed the event and are also
- not interested in subsequent actions from this event. Thus, you will not be called for any other actions
- within the event, such as a fingure gesture, or the eventual up action event.Remember that key events are always delivered to the View currently in focus. They are dispatched starting from the top
-of the View hierarchy, and then down, until they reach the appropriate destination. If your View (or a child of your View)
-currently has focus, then you can see the event travel through the {@link android.view.View#dispatchKeyEvent(KeyEvent)
-dispatchKeyEvent()} method. As an alternative to capturing key events through your View, you can also receive
-all of the events inside your Activity with {@link android.app.Activity#onKeyDown(int,KeyEvent) onKeyDown()}
-and {@link android.app.Activity#onKeyUp(int,KeyEvent) onKeyUp()}.
Note: Android will call event handlers first and then the appropriate default -handlers from the class definition second. As such, returning true from these event listeners will stop -the propagation of the event to other event listeners and will also block the callback to the -default event handler in the View. So be certain that you want to terminate the event when you return true.
- - -If you're building a custom component from View, then you'll be able to define several callback methods -used as default event handlers. -In the document on Building Custom Components, -you'll learn see some of the common callbacks used for event handling, including:
-{@link android.view.View#onKeyDown} - Called when a new key event occurs.{@link android.view.View#onKeyUp} - Called when a key up event occurs.{@link android.view.View#onTrackballEvent} - Called when a trackball motion event occurs.{@link android.view.View#onTouchEvent} - Called when a touch screen motion event occurs.{@link android.view.View#onFocusChanged} - Called when the view gains or loses focus.There are some other methods that you should be awere of, which are not part of the View class, -but can directly impact the way you're able to handle events. So, when managing more complex events inside -a layout, consider these other methods:
-{@link android.app.Activity#dispatchTouchEvent(MotionEvent)
- Activity.dispatchTouchEvent(MotionEvent)} - This allows your {@link
- android.app.Activity} to intercept all touch events before they are dispatched to the window.{@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)
- ViewGroup.onInterceptTouchEvent(MotionEvent)} - This allows a {@link
- android.view.ViewGroup} to watch events as they are dispatched to child Views.{@link android.view.ViewParent#requestDisallowInterceptTouchEvent(boolean)
- ViewParent.requestDisallowInterceptTouchEvent(boolean)} - Call this
- upon a parent View to indicate that it should not intercept touch events with {@link
- android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)}.-When a user is navigating a user interface with directional keys or a trackball, it is -necessary to give focus to actionable items (like buttons) so the user can see -what will accept input. If the device has touch capabilities, however, and the user -begins interacting with the interface by touching it, then it is no longer necessary to -highlight items, or give focus to a particular View. Thus, there is a mode -for interaction named "touch mode." -
--For a touch-capable device, once the user touches the screen, the device -will enter touch mode. From this point onward, only Views for which -{@link android.view.View#isFocusableInTouchMode} is true will be focusable, such as text editing widgets. -Other Views that are touchable, like buttons, will not take focus when touched; they will -simply fire their on-click listeners when pressed. -
--Any time a user hits a directional key or scrolls with a trackball, the device will -exit touch mode, and find a view to take focus. Now, the user may resume interacting -with the user interface without touching the screen. -
--The touch mode state is maintained throughout the entire system (all windows and activities). -To query the current state, you can call -{@link android.view.View#isInTouchMode} to see whether the device is currently in touch mode. -
- - -The framework will handle routine focus movement in response to user input.
-This includes changing the focus as Views are removed or hidden, or as new
-Views become available. Views indicate their willingness to take focus
-through the {@link android.view.View#isFocusable()} method. To change whether a View can take
-focus, call {@link android.view.View#setFocusable(boolean) setFocusable()}. When in touch mode,
-you may query whether a View allows focus with {@link android.view.View#isFocusableInTouchMode()}.
-You can change this with {@link android.view.View#setFocusableInTouchMode(boolean) setFocusableInTouchMode()}.
-
Focus movement is based on an algorithm which finds the nearest neighbor in a -given direction. In rare cases, the default algorithm may not match the -intended behavior of the developer. In these situations, you can provide -explicit overrides with the following XML attributes in the layout file: -nextFocusDown, nextFocusLeft, nextFocusRight, and -nextFocusUp. Add one of these attributes to the View from which -the focus is leaving. Define the value of the attribute to be the id of the View -to which focus should be given. For example:
--<LinearLayout - android:orientation="vertical" - ... > - <Button android:id="@+id/top" - android:nextFocusUp="@+id/bottom" - ... /> - <Button android:id="@+id/bottom" - android:nextFocusDown="@+id/top" - ... /> -</LinearLayout> -- -
Ordinarily, in this vertical layout, navigating up from the first Button would not go -anywhere, nor would navigating down from the second Button. Now that the top Button has -defined the bottom one as the nextFocusUp (and vice versa), the navigation focus will -cycle from top-to-bottom and bottom-to-top.
- -If you'd like to declare a View as focusable in your UI (when it is traditionally not),
-add the android:focusable XML attribute to the View, in your layout declaration.
-Set the value true. You can also declare a View
-as focusable while in Touch Mode with android:focusableInTouchMode.
To request a particular View to take focus, call {@link android.view.View#requestFocus()}.
To listen for focus events (be notified when a View receives or looses focus), use
-{@link android.view.View.OnFocusChangeListener#onFocusChange(View,boolean) onFocusChange()},
-as discussed in the Event Listeners section, above.
Android offers a sophisticated and powerful componentized model for building your UI, based on the fundamental building block classes {@link android.view.View} and {@link android.view.ViewGroup}. To start with, the platform includes a variety of prebuilt View and ViewGroup subclasses — called widgets and layouts, respectively — that you can use to construct your UI. The widgets and layouts are fully implemented and handle all of their own measuring and drawing, so you can use them right away. You can make new types of UI elements simply by nesting and grouping the widgets and layouts. Using widgets and layouts is the recommended approach to building a UI for your applications.
- -A partial list of available widgets includes {@link android.widget.Button Button}, -{@link android.widget.TextView TextView}, -{@link android.widget.EditText EditText}, -{@link android.widget.ListView ListView}, -{@link android.widget.CheckBox CheckBox}, -{@link android.widget.RadioButton RadioButton}, -{@link android.widget.Gallery Gallery}, -{@link android.widget.Spinner Spinner}, and the more special-purpose -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, -{@link android.widget.ImageSwitcher ImageSwitcher}, and -{@link android.widget.TextSwitcher TextSwitcher}.
- -Among the layouts available are {@link android.widget.LinearLayout LinearLayout}, -{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.AbsoluteLayout AbsoluteLayout}, and others. For more examples, see Common Layout Objects.
- -If none of the prebuilt widgets or layouts meets your needs, you can also create your own View subclass, such as a layout group or compound control. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods. -
- -Creating your own View subclasses gives you precise control over the appearance and function of a screen element. To give an idea of the control you get with custom views, here are some examples of what you could do with them:
- --The sections below explain how to create custom Views and use them in your application. -For detailed reference information, see the {@link android.view.View} class.
- -This document covers the following:
--These steps provide a high level overview of -what you need to know to get started in creating your own -View components:
- -on', for
- example, {@link android.view.View#onDraw onDraw()},
- {@link android.view.View#onMeasure onMeasure()}, and
- {@link android.view.View#onKeyDown onKeyDown()}.
- on... events in {@link android.app.Activity
- Activity} or {@link android.app.ListActivity ListActivity}
- that you override for life cycle and other functionality hooks.
- Tip: - Extension classes can be defined as inner classes inside the activities - that use them. This is useful because it controls access to them but - isn't necessary (perhaps you want to create a new public View for - wider use in your application). -
- - --Fully customized components can be used to create graphical components that -appear however you wish. Perhaps a graphical VU -meter that looks like an old analog gauge, or a sing-a-long text view where -a bouncing ball moves along the words so you can sing along with a karaoke -machine. Either way, you want something that the built-in components just -won't do, no matter how you combine them.
-Fortunately, you can easily create components that look and behave in any -way you like, limited perhaps only by your imagination, the size of the -screen, and the available processing power (remember that ultimately your -application might have to run on something with significantly less power -than your desktop workstation).
-To create a fully customized component:
-onMeasure() and
- are also likely to need to override onDraw() if you want
- the component to show something. While both have default behavior,
- the default onDraw() will do nothing, and the default
- onMeasure() will always set a size of 100x100 — which is
- probably not what you want.
- on... methods may also be overridden as required.
- onDraw() and onMeasure()onDraw() delivers you a {@link android.graphics.Canvas Canvas}
-upon which you can implement anything you want: 2D graphics, other standard or
-custom components, styled text, or anything else you can think of.
Note: -Except for 3D graphics. If you want to -use 3D graphics, you must extend {@link android.view.SurfaceView SurfaceView} -instead of View, and draw from a seperate thread. See the -GLSurfaceViewActivity sample -for details.
-onMeasure() is a little more involved. onMeasure()
-is a critical piece of the rendering contract between your component and its
-container. onMeasure() should be overridden to efficiently and
-accurately report the measurements of its contained parts. This is made
-slightly more complex by the requirements of limits from the parent
-(which are passed in to the onMeasure() method) and by the
-requirement to call the setMeasuredDimension() method with the
-measured width and height once they have been calculated. If you fail to
-call this method from an overridden onMeasure() method, the
-result will be an exception at measurement time.
At a high level, implementing onMeasure() looks something
- like this:
onMeasure() method is called with width and
- height measure specifications (widthMeasureSpec and
- heighMeasureSpec parameters, both are integer codes
- representing dimensions) which should be treated as requirements for
- the restrictions on the width and height measurements you should produce. A
- full reference to the kind of restrictions these specifications can require
- can be found in the reference documentation under {@link
- android.view.View#onMeasure View.onMeasure(int, int)} (this reference
- documentation does a pretty good job of explaining the whole measurement
- operation as well).
- onMeasure() method should calculate a
- measurement width and height which will be required to render the
- component. It should try to stay within the specifications passed in,
- although it can choose to exceed them (in this case, the parent can
- choose what to do, including clipping, scrolling, throwing an exception,
- or asking the onMeasure() to try again, perhaps with
- different measurement specifications).
- setMeasuredDimension(int
- width, int height) method must be called with the calculated
- measurements. Failure to do this will result in an exception being
- thrown.
- -Here's a summary of some of the other standard methods that the framework calls on views: -
-| Category | Methods | Description |
|---|---|---|
| Creation | -Constructors | -There is a form of the constructor that are called when the view - is created from code and a form that is called when the view is - inflated from a layout file. The second form should parse and apply - any attributes defined in the layout file. - | -
{@link android.view.View#onFinishInflate()} |
- Called after a view and all of its children has been inflated - from XML. | -|
| Layout | -{@link android.view.View#onMeasure} |
- Called to determine the size requirements for this view and all - of its children. - | -
{@link android.view.View#onLayout} |
- Called when this view should assign a size and position to all - of its children. - | -|
{@link android.view.View#onSizeChanged} |
- Called when the size of this view has changed. - | -|
| Drawing | -{@link android.view.View#onDraw} |
- Called when the view should render its content. - | -
| Event processing | -{@link android.view.View#onKeyDown} |
- Called when a new key event occurs. - | -
{@link android.view.View#onKeyUp} |
- Called when a key up event occurs. - | -|
{@link android.view.View#onTrackballEvent} |
- Called when a trackball motion event occurs. - | -|
{@link android.view.View#onTouchEvent} |
- Called when a touch screen motion event occurs. - | -|
| Focus | -{@link android.view.View#onFocusChanged} |
- Called when the view gains or loses focus. - | -
{@link android.view.View#onWindowFocusChanged} |
- Called when the window containing the view gains or loses focus. - | -|
| Attaching | -{@link android.view.View#onAttachedToWindow()} |
- Called when the view is attached to a window. - | -
{@link android.view.View#onDetachedFromWindow} |
- Called when the view is detached from its window. - | -|
{@link android.view.View#onWindowVisibilityChanged} |
- Called when the visibility of the window containing the view - has changed. - | -
The CustomView sample in the -API Demos provides an example -of a customized View. The custom View is defined in the -LabelView -class.
-The LabelView sample demonstrates a number of different aspects of custom components:
-setText(), setTextSize(),
- setTextColor() and so on.onMeasure method to determine and set the
- rendering size of the component. (Note that in LabelView, the real work is done
- by a private measureWidth() method.)onDraw() method to draw the label onto the
- provided canvas.You can see some sample usages of the LabelView custom View in
-custom_view_1.xml
-from the samples. In particular, you can see a mix of both android:
-namespace parameters and custom app: namespace parameters. These
-app: parameters are the custom ones that the LabelView recognizes
-and works with, and are defined in a styleable inner class inside of the
-samples R resources definition class.
If you don't want to create a completely customized component, but instead -are looking to put together a reusable component that consists of a group of -existing controls, then creating a Compound Component (or Compound Control) might -fit the bill. In a nutshell, this brings together a number of more atomic -controls (or views) into a logical group of items that can be treated as a -single thing. For example, a Combo Box can be thought of as a -combination of a single line EditText field and an adjacent button with an attached - PopupList. If you press the button and select -something from the list, it populates the EditText field, but the user can -also type something directly into the EditText if they prefer.
-In Android, there are actually two other Views readily available to do -this: {@link android.widget.Spinner Spinner} and -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, but -regardless, the concept of a Combo Box makes an easy-to-understand -example.
-To create a compound component:
-onDraw() and onMeasure() methods since the
- layout will have default behavior that will likely work just fine. However,
- you can still override them if you need to.
- on... methods, like
- onKeyDown(), to perhaps choose certain default values from
- the popup list of a combo box when a certain key is pressed.
- - To summarize, the use of a Layout as the basis for a Custom Control has a -number of advantages, including:
- -onDraw() and onMeasure() methods (plus
- most of the other on... methods) will likely have suitable behavior so
- you don't have to override them.
- In the API Demos project
- that comes with the SDK, there are two List
- examples — Example 4 and Example 6 under Views/Lists demonstrate a
- SpeechView which extends LinearLayout to make a component for displaying
- Speech quotes. The corresponding classes in the sample code are
- List4.java and List6.java.
There is an even easier option for creating a custom View which is -useful in certain circumstances. If there is a component that is already very -similar to what you want, you can simply extend that component and just -override the behavior that you want to change. You can do all of the things -you would do with a fully customized component, but by starting with a more -specialized class in the View heirarchy, you can also get a lot of behavior for -free that probably does exactly what you want.
-For example, the SDK includes a NotePad application in the -samples. This demonstrates many aspects of using the Android platform, among -them is extending an EditText View to make a lined notepad. This is not a -perfect example, and the APIs for doing this might change from this early -preview, but it does demonstrate the principles.
-If you haven't done so already, import the
-NotePad sample into Eclipse (or
-just look at the source using the link provided). In particular look at the definition of
-MyEditText in the NoteEditor.java
-file.
Some points to note here
-The class is defined with the following line:
-public static class MyEditText extends EditTextNoteEditor
- activity, but it is public so that it could be accessed as
- NoteEditor.MyEditText from outside of the NoteEditor
- class if desired.
- static, meaning it does not generate the so-called
- "synthetic methods" that allow it to access data from the parent
- class, which in turn means that it really behaves as a separate
- class rather than something strongly related to NoteEditor.
- This is a cleaner way to create inner classes if they do not need
- access to state from the outer class, keeps the generated class
- small, and allows it to be used easily from other classes.
- EditText, which is the View we have chosen to
- customize in this case. When we are finished, the new class will be
- able to substitute for a normal EditText view.As always, the super is called first. Furthermore, - this is not a default constructor, but a parameterized one. The - EditText is created with these parameters when it is inflated from an - XML layout file, thus, our constructor needs to both take them and pass them - to the superclass constructor as well.
-In this example, there is only one method to be overridden:
- onDraw() — but there could easily be others needed when you
- create your own custom components.
For the NotePad sample, overriding the onDraw() method allows
- us to paint the blue lines on the EditText view canvas (the
- canvas is passed into the overridden onDraw() method). The
- super.onDraw() method is called before the method ends. The
- superclass method should be invoked, but in this case, we do it at the
- end after we have painted the lines we want to include.
We now have our custom component, but how can we use it? In the
- NotePad example, the custom component is used directly from the
- declarative layout, so take a look at note_editor.xml in the
- res/layout folder.
-<view xmlns:android="http://schemas.android.com/apk/res/android" - class="com.android.notepad.NoteEditor$MyEditText" - id="@+id/note" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:background="@android:drawable/empty" - android:padding="10dip" - android:scrollbars="vertical" - android:fadingEdge="vertical" />- -
NoteEditor$MyEditText notation which is a standard way to
- refer to inner classes in the Java programming language.
- And that's all there is to it. Admittedly this is a simple case, but -that's the point — creating custom components is only as complicated as you -need it to be.
-A more sophisticated component may override even more on... methods and
-introduce some of its own helper methods, substantially customizing its properties and
-behavior. The only limit is your imagination and what you need the component to
-do.
The basic functional unit of an Android application is the activity — an object of the class {@link android.app.Activity android.app.Activity}. An activity can do many things, but by itself it does not have a presence on the screen. To give your activity a screen presence and design its UI, you work with views and viewgroups -- basic units of user interface expression on the Android platform.
- -A view is an object of base class {@link android.view.View android.view.View}. It's a data structure whose properties store the layout and content for a specific rectangular area of the screen. A View object handles measuring and layout, drawing, focus change, scrolling, and key/gestures for the screen area it represents.
-The View class serves as a base class for widgets — a set of fully implemented subclasses that draw interactive screen elements. Widgets handle their own measuring and drawing, so you can use them to build your UI more quickly. The list of widgets available includes Text, EditText, InputMethod, MovementMethod, Button, RadioButton, Checkbox, and ScrollView.
- -A viewgroup is an object of class {@link android.view.ViewGroup android.view.Viewgroup}. As its name indicates, a viewgroup is a special type of view object whose function is to contain and manage a subordinate set of views and other viewgroups, Viewgroups let you add structure to your UI and build up complex screen elements that can be addressed as a single entity.
- -The Viewgroup class serves as a base class for layouts — a set of fully implemented subclasses that provide common types of screen layout. The layouts give you a way to build a structure for a set of views.
- -On the Android platform, you define an Activity's UI using a tree of view and viewgroup nodes, as shown in the diagram below. The tree can be as simple or complex as you need to make it, and you can build it up using Android's set of predefined widgets and layouts or custom view types that you create yourself.
- -
-
-To attach the tree to the screen for rendering, your Activity calls its setContentView() method and passes a reference to the root node object. Once the Android system has the reference to the root node object, it can work directly with the node to invalidate, measure, and draw the tree. When your Activity becomes active and receives focus, the system notifies your activity and requests the root node to measure and draw the tree. The root node then requests that its child nodes draw themselves — in turn, each viewgroup node in the tree is responsible for drawing its direct children.
- -As mentioned previously, each view group has the responsibility of - measuring its available space, laying out its children, and calling Draw() on - each child to let it render itself. The children may request a size and location - in the parent, but the parent object has the final decision on where how big - each child can be.
- -Every viewgroup class uses a nested class that extends {@link -android.view.ViewGroup.LayoutParams ViewGroup.LayoutParams}. This subclass - contains property types that define a child's size and position, in properties - appropriate for that view group class.
- -
-
-Note that every LayoutParams subclass has its own syntax for setting -values. Each child element must define LayoutParams that are appropriate for its parent, although it may define different LayoutParams for its children.
- -All viewgroups include width and height. Many also include margins and -borders. You can specify width and height exactly, though you probably won't want -to do this often. More often you will tell your view to size itself either to -the dimensions of its content, or to become as big as its containing object -will allow.
- diff --git a/docs/html/guide/topics/views/ui-xml.jd b/docs/html/guide/topics/views/ui-xml.jd deleted file mode 100644 index 8ae599c..0000000 --- a/docs/html/guide/topics/views/ui-xml.jd +++ /dev/null @@ -1,133 +0,0 @@ -page.title=Declaring a UI in XML -parent.title=Views and Layout -parent.link=index.html -@jd:body - -You can create your application's user interface in two ways: -
One advantage of declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls it's behavior. Your UI description is external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations and for a variety of device screen sizes or languages. Additionally, declaring in XML makes it easier to see the elements and structure of your UI, so it's easier to debug problems.
- -The Android framework gives you the flexibility to use either or both of these ways of declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.
- -You build your application's UI in approximately the same way, whether you are declaring it in XML or programmatically. In both cases, your UI will be a tree structure that may include multiple View or Viewgroup subclasses.
- -
In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the framework's UI-related classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element.
- -However, note that the XML vocabulary for defining UI is not entirely identical to the framework's classes and methods. In some cases, there are slight naming differences. For
-example, the EditText element has a text attribute that corresponds to
-EditText.setText.
For your convenience, the API reference documentation for UI related classes lists the available XML attributes that correspond to the class methods, including inherited attributes.
- -To learn more about the available XML elements and attributes, as well as the format of the XML file, see Layout Resources.
-Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create HTML files — as a series of nested tags.
- -Each layout file must contain exactly one root element, and the root element must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or controls as child elements of the root element, if needed. In the example below, the tree of XML elements evaluates to the outermost LinearLayout object. - -
After you've declared your layout in XML, you must save the file, with the .xml extension, in the proper location, so that it will be compiled correctly. The proper location for storing layout files is in your application's res/layout/ directory.
When you compile your application, each XML layout file is compiled into an
-android.view.View resource. You can then load the layout resource from your application code, by calling setContentView(R.layout.layout_file_name) in your {@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()}
-implementation.
When you load a layout resource, the Android system initializes run-time objects corresponding to the elements in your layout. It parses the elements of your layout in-order (depth-first), instantiating the Views and adding them to their parent(s).
- -Attributes named layout_something apply to that
-object's LayoutParams member. Layout
-Resources also describes how to learn the syntax for specifying
-LayoutParams properties.
Also note that Android draws elements in the order in which they -appear in the XML. Therefore, if elements overlap, the last one in the XML -file will probably be drawn on top of any previously listed elements in that -same space.
- -The following values are supported for dimensions (described in {@link -android.util.TypedValue TypedValue}):
- -Example: android:layout_width="25px"
For more information about these dimensions, see Dimension Values.
- -The example below shows an XML file and the resulting screen in the UI. Note that the text on the -top of the screen was set by calling {@link -android.app.Activity#setTitle(java.lang.CharSequence) Activity.setTitle}. Note -that the attributes that refer to relative elements (i.e., layout_toLeft) -refer to the ID using the syntax of a relative resource -(@id/id_number).
- -
- <?xml version="1.0" encoding="utf-8"?> -<!-- Demonstrates using a relative layout to create a form --> -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:background="@drawable/blue" - android:padding="10px"> - - <TextView id="@+id/label" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:text="Type here:"/> - - <EditText id="@+id/entry" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:background="@android:drawable/editbox_background" - android:layout_below="@id/label"/> - - <Button id="@+id/ok" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_below="@id/entry" - android:layout_alignParentRight="true" - android:layout_marginLeft="10px" - android:text="OK" /> - - <Button android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_toLeftOf="@id/ok" - android:layout_alignTop="@id/ok" - android:text="Cancel" /> -</RelativeLayout> |
- ![]() |
-
Loading the compiled layout resource is very easy, and done with a single -call in the activity's onCreate() method, as shown here:
- -
-protected void onCreate(Bundle savedValues)
-{
- // Be sure to call the super class.
- super.onCreate(savedValues);
-
- // Load the compiled layout resource into the window's
- // default ViewGroup.
- // The source file is res/layout/hello_activity.xml
- setContentView(R.layout.hello_activity);
-
- // Retrieve any important stored values.
- restoreValues(savedValues);
-}
diff --git a/docs/html/guide/topics/wireless/bluetooth.jd b/docs/html/guide/topics/wireless/bluetooth.jd
deleted file mode 100644
index 710cd4c..0000000
--- a/docs/html/guide/topics/wireless/bluetooth.jd
+++ /dev/null
@@ -1,18 +0,0 @@
-page.title=Bluetooth
-parent.title=Wireless Controls
-parent.link=index.html
-@jd:body
-
-The Wi-Fi APIs provide a means by which application can communicate with the lower-level -wireless stack that provides Wi-Fi network access. Almost all information from the device supplicant -is available, including the connected network's link speed, IP address, negotiation state, and more. -It also provides information about all non-connected available networks. Some of the available network -interactions include the ability to scan, add, dave, terminate and initiate connections.
- - -The Bluetooth APIs allow applications to scan, connect and pair with other Bluetooth devices. -THESE APIS ARE NOT YET AVAILABLE.
- - - diff --git a/docs/html/guide/topics/wireless/wifi.jd b/docs/html/guide/topics/wireless/wifi.jd deleted file mode 100644 index 520feaf..0000000 --- a/docs/html/guide/topics/wireless/wifi.jd +++ /dev/null @@ -1,18 +0,0 @@ -page.title=Wi-Fi -parent.title=Wireless Controls -parent.link=index.html -@jd:body - -First impressions matter, and as a developer you know that the first impression -you get of a development framework is how easy it is to write "Hello, -World!" Well, in Android, it's pretty easy. Here's how it looks:
- - - -The sections below spell it all out in detail.
- - -Let's jump in!
- - - -Creating the project is as simple as can be. An Eclipse -plugin is available making Android development a snap.
- -You'll need to have a development computer with the Eclipse IDE installed (see System and Software Requirements), and -you'll need to install the Android Eclipse Plugin (ADT). Once you have those ready, come back here.
- -First, here's a high-level summary of how to build "Hello, World!":
- -That's it! Next, let's go through each step above in detail.
-From Eclipse, select the File > New > Project menu item. If the Android - Plugin for Eclipse has been successfully installed, the resulting dialog - should have a folder labeled "Android" which should contain a single entry: - "Android Project".
- -
Once you've selected "Android Project", click the Next button.
-The next screen allows you to enter the relevant details for your project. - Here's an example:
- -
Here's what each field on this screen means:
- - -| Project Name | -This is the name of the directory or folder on your computer that you - want to contain the project. | -
| Package Name | -This is the package namespace (following the same rules as for - packages in the Java programming language) that you want all your source code to - reside under. This also sets the package name under which the stub - Activity will be generated. - The package name you use in your application must be unique across - all packages installed on the system; for this reason, it's very - important to use a standard domain-style package for your - applications. In the example above, we used the - package domain "com.android"; you should use a - different one appropriate to your organization. | -
| Activity Name | -This is the name for the class stub that will be generated by the plugin. - This will be a subclass of Android's Activity class. An Activity is simply a - class that can run and do work. It can create a UI if it chooses, but it - doesn't need to. | -
| Application Name | -This is the human-readable title for your application. | -
The checkbox for toggling "Use default location" allows you to change the -location on disk where the project's files will be generated and stored.
-After the plugin runs, you'll have a class named HelloAndroid -(found in your package, HelloAndroid > src > com.android.hello). It should look like -this:
- -public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
-}
-
-Now, you could run this right away, but let's go a little further, -so we understand more about what's happening. -So, the next step is to modify some code!
-Take a look at this revised code, below, and make the same changes to your HelloAndroid.java file. We'll dissect -it line by line:
- -
-package com.android.hello;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.widget.TextView;
-
-public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- TextView tv = new TextView(this);
- tv.setText("Hello, Android");
- setContentView(tv);
- }
-}
-
-Tip: If you forgot to import the TextView package, try this: -press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse -shortcut to organize imports—it identifies missing packages and adds them for you.
- -In Android, user interfaces are composed of hierarchies of classes called -Views. A View is simply a drawable object, such as a radio button, an -animation, or (in our case) a text label. The specific name for the View -subclass that handles text is simply TextView.
- -Here's how you construct a TextView:
- -TextView tv = new TextView(this);- -
The argument to TextView's constructor is an Android Context instance. The
-Context is simply a handle to the system; it provides services like
-resolving resources, obtaining access to databases and preferences, and so
-on. The Activity class inherits from Context. Since our
-HelloAndroid class is a subclass of Activity, it is also a Context, and so we can
-pass the this reference to the TextView.
Once we've constructed the TextView, we need to tell it what to display:
- -tv.setText("Hello, Android");
-
-Nothing too surprising there.
- -At this point, we've constructed a TextView and told it what text to -display. The final step is to connect this TextView with the on-screen -display, like so:
- -setContentView(tv);- -
The setContentView() method on Activity indicates to the system which
-View should be associated with the Activity's UI. If an Activity doesn't
-call this method, no UI is present at all and the system will display a blank
-screen. For our purposes, all we want is to display some text, so we pass it
-the TextView we just created.
There it is — "Hello, World" in Android! The next step, of course, is -to see it running.
- - - -The Eclipse plugin makes it very easy to run your applications. Begin by -selecting the Run > Open Run Dialog menu entry (in Eclipse 3.4, it's -Run > Run Configurations). You should see a dialog -like this:
- -
-Next, highlight the "Android Application" entry, and then click the icon in the -top left corner (the one depicting a sheet of paper with a plus sign in the -corner) or simply double-click the "Android Application" entry. You should -have a new launcher entry named "New_configuration".
- -
-Change the name to something expressive, like "Hello, Android", and then pick -your project by clicking the Browse button. (If you have more than one -Android project open in Eclipse, be sure to pick the right one.) The -plugin will automatically scan your project for Activity subclasses, and add -each one it finds to the drop-down list under the "Activity:" label. Since -your "Hello, Android" project only has one, it will be the default, and you can -simply continue.
- -Click the "Apply" button. Here's an example:
- -
-That's it — you're done! Click the Run button, and the Android Emulator -should start. Once it's booted up your application will appear. When all is said and done, you should -see something like this:
- -
-That's "Hello, World" in Android. Pretty straightforward, eh? -The next sections of the tutorial offer more detailed information that you may find valuable as you -learn more about Android.
- - - -The "Hello, World" example you just completed uses what we call "programmatic" -UI layout. This means that you construct and build your application's UI -directly in source code. If you've done much UI programming, you're -probably familiar with how brittle that approach can sometimes be: small -changes in layout can result in big source-code headaches. It's also very -easy to forget to properly connect Views together, which can result in errors in -your layout and wasted time debugging your code.
- -That's why Android provides an alternate UI construction model: XML-based -layout files. The easiest way to explain this concept is to show an -example. Here's an XML layout file that is identical in behavior to the -programmatically-constructed example you just completed:
- -<?xml version="1.0" encoding="utf-8"?> -<TextView xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:text="Hello, Android"/>- -
The general structure of an Android XML layout file is simple. It's a tree -of tags, where each tag is the name of a View class. In this example, it's -a very simple tree of one element, a TextView. You can use the -name of any class that extends View as a tag name in your XML layouts, -including custom View classes you define in your own code. This -structure makes it very easy to quickly build up UIs, using a much simpler -structure and syntax than you would in source code. This model is inspired -by the web development model, where you can separate the presentation of your -application (its UI) from the application logic used to fetch and fill in data.
- -In this example, there are also four XML attributes. Here's a summary of what -they mean:
- -| - Attribute - | -- Meaning - | -
|---|---|
- xmlns:android
- |
-
- This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. - |
-
- android:layout_width
- |
-
- This attribute defines how much of the available width on the screen this View should consume. In this case, it's our only View so we want it to take up the entire screen, which is what a value of "fill_parent" means. - |
-
- android:layout_height
- |
- - This is just like android:layout_width, except that it refers to available screen height. - | -
- android:text
- |
- - This sets the text that the TextView should contain. In this example, it's our usual "Hello, Android" message. - | -
So, that's what the XML layout looks like, but where do you put it? Under the /res/layout directory in your project. The "res" is -short for "resources" and that directory contains all the non-code assets that -your application requires. This includes things like images, localized -strings, and XML layout files.
- -The Eclipse plugin creates one of these XML files for you. In our example -above, we simply never used it. In the Package Explorer, expand the -folder /res/layout, and edit the file main.xml. Replace its contents with -the text above and save your changes.
- -Now open the file named R.java in your source code folder in the Package -Explorer. You'll see that it now looks something like this:
- -
-public final class R {
- public static final class attr {
- };
- public static final class drawable {
- public static final int icon=0x7f020000;
- };
- public static final class layout {
- public static final int main=0x7f030000;
- };
- public static final class string {
- public static final int app_name=0x7f040000;
- };
-};
-
-
-A project's R.java file is an index into all the resources defined in the -file. You use this class in your source code as a sort of short-hand -way to refer to resources you've included in your project. This is -particularly powerful with the code-completion features of IDEs like Eclipse -because it lets you quickly and interactively locate the specific reference -you're looking for.
- -The important thing to notice for now is the inner class named "layout", and its -member field "main". The Eclipse plugin noticed that you added a new XML -layout file and then regenerated this R.java file. As you add other -resources to your projects you'll see R.java change to keep up.
- -The last thing you need to do is modify your HelloAndroid source code to use the new -XML version of your UI, instead of the hard-coded version. Here's what -your new class will look like. As you can see, the source code becomes much -simpler:
- -package com.android.hello;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
-}
-
-When you make this change, don't just copy-and-paste it in. Try out the code-completion feature on that R class. You'll probably find that it helps a lot.
- -Now that you've made this change, go ahead and re-run your application — all -you need to do is click the green Run arrow icon, or select -Run > Run History > Hello, Android from the menu. You should see.... well, exactly the same thing -you saw before! After all, the point was to show that the two different -layout approaches produce identical results.
- -There's a lot more to creating these XML layouts, but that's as far as we'll go -here. Read the Implementing a User Interface documentation for more -information on the power of this approach.
- - - -The Android Plugin for Eclipse also has excellent integration with the Eclipse -debugger. To demonstrate this, let's introduce a bug into -our code. Change your HelloAndroid source code to look like this:
- -
-package com.android.hello;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Object o = null;
- o.toString();
- setContentView(R.layout.main);
- }
-}
-
-This change simply introduces a NullPointerException into your code. If -you run your application again, you'll eventually see this:
- -
-Press "Force Quit" to terminate the application and close the emulator window.
- -To find out more about the error, set a breakpoint in your source code
-on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello,
-Android from the menu to enter debug mode. Your app will restart in the
-emulator, but this time it will suspend when it reaches the breakpoint you
-set. You can then step through the code in Eclipse's Debug Perspective,
-just as you would for any other application.
-If you don't use Eclipse (such as if you prefer another IDE, or simply use text -editors and command line tools) then the Eclipse plugin can't help you. -Don't worry though — you don't lose any functionality just because you don't -use Eclipse.
- -The Android Plugin for Eclipse is really just a wrapper around a set of tools -included with the Android SDK. (These tools, like the emulator, aapt, adb, -ddms, and others are documented elsewhere.) Thus, it's possible to -wrap those tools with another tool, such as an 'ant' build file.
- -The Android SDK includes a Python script named "activitycreator.py" that can be -used to create all the source code and directory stubs for your project, as well -as an ant-compatible build.xml file. This allows you to build your project -from the command line, or integrate it with the IDE of your choice.
- -For example, to create a HelloAndroid project similar to the one we just created -via Eclipse, you'd use this command:
- -activitycreator.py --out HelloAndroid com.android.hello.HelloAndroid- -
To build the project, you'd then run the command 'ant'. When that command -successfully completes, you'll be left with a file named HelloAndroid.apk under -the 'bin' directory. That .apk file is an Android Package, and can be -installed and run in your emulator using the 'adb' tool.
- -For more information on how to use these tools, please read the documentation -cited above.
diff --git a/docs/html/guide/tutorials/hello-world.jd b/docs/html/guide/tutorials/hello-world.jd deleted file mode 100644 index 7b9287f..0000000 --- a/docs/html/guide/tutorials/hello-world.jd +++ /dev/null @@ -1,500 +0,0 @@ -page.title=Hello, World -@jd:body - -As a developer, you know that the first impression -of a development framework is how easy it is to write "Hello, -World." Well, on Android, it's pretty easy. -It's particularly easy if you're using Eclipse as your IDE, because we've provided a -great plugin that handles your project creation and management to greatly speed up your -development cycles.
- -If you're not using Eclipse, that's okay. Familiarize yourself with -Developing in Other IDEs. -You can then come back here and ignore anything about Eclipse.
- -Before you start, you should already have the latest SDK installed, and if you're using -Eclipse, you should have installed the ADT plugin as well. See -Installing the Android SDK to get these -installed.
- -Note: -In some cases, you might want to click the screenshots below to get a bigger view. -
- -From Eclipse, select the File > New > Project menu item. If the Android - Plugin for Eclipse has been successfully installed, the resulting dialog - should have a folder labeled "Android" which should contain a single entry: - "Android Project".
-Selected "Android Project" and click Next.
- -
-
- The next screen allows you to enter the relevant details for your project:
-Click Finish.
-
-
- Here's what each field on this screen means:
- -The package name you use in your application must be unique across - all packages installed on the system; for this reason, it's very - important to use a standard domain-style package for your - applications. In the example above, we used the - package domain "com.android"; you should use a - different one appropriate to your organization.
The checkbox for toggling "Use default location" allows you to change - the location on disk where the project's files will be generated and stored.
- -After the plugin completes your project creations, you'll have a class named HelloAndroid
-(found in your project package, HelloAndroid > src > com.android.hello). It should look like
-this:
-package com.example.hello;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
-}
-
-Now let's modify some code!
-Take a look at this revised code, below, and make the same changes to your HelloAndroid.java file. We'll dissect -it line by line:
- -
-package com.android.hello;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.widget.TextView;
-
-public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- TextView tv = new TextView(this);
- tv.setText("Hello, Android");
- setContentView(tv);
- }
-}
-
-Tip: If you forgot to import the TextView package, try this: -press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse -shortcut to organize imports—it identifies missing packages and adds them for you.
- -Notice that our class is based on the {@link android.app.Activity} class. An Activity is a -single application entity that is used to perform actions. An application may have many, but the user -interacts with them only one at a time. An Activity is not required to actually have a user interface, -but usually will.
- -An Android user interface is composed of hierarchies of objects called -Views. A {@link android.view.View} is simply a drawable object, such as a radio button, an -animation, or (in our case) a text label. The specific name for the View -subclass that handles text, which we use here, is {@link android.widget.TextView}.
- -Here's how you construct a TextView:
- -TextView tv = new TextView(this);- -
The argument to TextView's constructor is an Android {@link android.content.Context} instance. The
-Context is simply a handle to the system; it provides services like
-resolving resources, obtaining access to databases and preferences, and so
-on. The Activity class inherits from Context. Since our
-HelloAndroid class is a subclass of Activity, it is also a Context, and so we can
-pass the this reference to the TextView.
Once we've constructed the TextView, we need to tell it what to display:
- -tv.setText("Hello, Android");
-
-Nothing too surprising there.
- -At this point, we've constructed a TextView and told it what text to -display. The final step is to connect this TextView with the on-screen -display, like so:
- -setContentView(tv);- -
The setContentView() method on Activity indicates to the system which
-View should be associated with the Activity's UI. If an Activity doesn't
-call this method, no UI is present at all and the system will display a blank
-screen. For our purposes, all we want is to display some text, so we pass it
-the TextView we just created.
There it is — "Hello, World" in Android! The next step, of course, is -to see it running.
- - - -The Eclipse plugin makes it very easy to run your applications. Begin by -selecting the Run > Open Run Dialog menu entry (in Eclipse 3.4, it's -Run > Run Configurations). You should see a dialog -like this:
- -
-
-Next, highlight the "Android Application" entry, and then click the icon in the -top left corner (the one depicting a sheet of paper with a plus sign in the -corner) or simply double-click the "Android Application" entry. You should -have a new launcher entry named "New_configuration".
- -
-
-Change the name to something expressive, like "Hello, Android", and then pick -your project by clicking the Browse button. (If you have more than one -Android project open in Eclipse, be sure to pick the right one.) The -plugin will automatically scan your project for Activity subclasses, and add -each one it finds to the drop-down list under the "Activity:" label. Since -your "Hello, Android" project only has one, it will be the default, and you can -simply continue.
- -Click the "Apply" button. Here's an example:
- -
-
-Now click Run, and the Android Emulator should start and open the application. -Once it's booted up your application will appear. (Once booted, you may need to unlock the emulator's phone screen -by pressing the device MENU key.) When all is said and done, you should -see something like this:
- -
-
-
-That's "Hello, World" in Android. Pretty straightforward, eh? -The next sections of the tutorial offer more detailed information that you may find valuable as you -learn more about Android.
- - - - -The "Hello, World" example you just completed uses what we call "programmatic" -UI layout. This means that you construct and build your application's UI -directly in source code. If you've done much UI programming, you're -probably familiar with how brittle that approach can sometimes be: small -changes in layout can result in big source-code headaches. It's also very -easy to forget to properly connect Views together, which can result in errors in -your layout and wasted time debugging your code.
- -That's why Android provides an alternate UI construction model: XML-based -layout files. The easiest way to explain this concept is to show an -example. Here's an XML layout file that is identical in behavior to the -programmatically-constructed example you just completed:
- -<?xml version="1.0" encoding="utf-8"?> -<TextView xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:text="@string/hello"/>- -
The general structure of an Android XML layout file is simple: it's a tree -of XML elements, where each element is the name of a View class -(this example, however, is just one element). You can use the -name of any class that extends {@link android.view.View} as an element in your XML layouts, -including custom View classes you define in your own code. This -structure makes it very easy to quickly build up UIs, using a more simple -structure and syntax than you would in source code. This model is inspired -by the web development model, where you can separate the presentation of your -application (its UI) from the application logic used to fetch and fill in data.
- -In this example, there's just one View element, the TextView,
-which has four XML attributes. Here's a summary of what they mean:
| - Attribute - | -- Meaning - | -
|---|---|
- xmlns:android
- |
-
- This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. - |
-
- android:layout_width
- |
-
- This attribute defines how much of the available width on the screen this View should consume. In this case, it's our only View so we want it to take up the entire screen, which is what a value of "fill_parent" means. - |
-
- android:layout_height
- |
- - This is just like android:layout_width, except that it refers to available screen height. - | -
- android:text
- |
- - This sets the text that the TextView should display. In this example, we use a string - resource instead of a hard-coded string value. - The hello string is defined in the res/values/strings.xml file. This is the - recommended practice for inserting strings to your application, because it makes the localization - of your application to other languages graceful, without need to hard-code changes to the layout file. - For more information, see Resources - and Internationalization. - | -
These layout files belong in the res/layout/ directory in your project. The "res" is -short for "resources" and that directory contains all the non-code assets that -your application requires. Resources also include things like images, localized -strings, and XML layout files.
- -When you want a different design for landscape, put your layout XML file
- in res/layout-land/. Android will automatically look here when the layout changes.
- Without it the layout will just be stretched.
The Eclipse plugin automatically creates one of these layout files for you (main.xml). In our example
-above, we just ignored it and created our layout programmatically. We did so just to teach you a little more
-about the framework, but you should almost always define your layout in an XML file instead of in your code.
So, let's put it to use and change the "Hello, Android" sample to use the XML layout.
- -main.xml (once opened, you might need to click
-the "main.xml" tab at the bottom to see the XML source). Replace its contents with
-the following XML:
-<?xml version="1.0" encoding="utf-8"?> -<TextView xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:text="@string/hello"/>-
Save the file.
-strings.xml.
-This is where you should save all default text strings for your user interface. If you're using Eclipse, then
-ADT will have started you with two strings, hello and app_name.
-Revise hello to something else. Perhaps "Hello, Android! I am a string resource!"
-The entire file should now look like this:
--<?xml version="1.0" encoding="utf-8"?> -<resources> - <string name="hello">Hello, Android! I am a string resource!</string> - <string name="app_name">Hello, Android</string> -</resources> --
HelloAndroid class source code to read the
-XML layout, instead of the hard-coded version. Edit the file to look like this:
-
-package com.example.hello;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
-}
-
-When you make this change, type it by hand to try the code-completion feature on that R class. You'll probably find that it helps a lot.
- -Now, instead of passing setContentView() a View object, we give it a reference to our layout resource.
-The resource is identified as R.layout.main, which is actually a compiled object representation of
-the layout defined in layout/main.xml. The Eclipse plugin automatically creates this reference for
-us inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you
-when you run Ant to build the application. (More about the R class in a moment.)
Now that you've made this change, go ahead and re-run your application — all -you need to do is click the green Run arrow icon, or select -Run > Run History > Hello, Android from the menu. You should see pretty much the same thing -you saw before! After all, the point was to show that the two different -layout approaches produce identical results.
- -Tip: Use the shortcut Ctrl-Shift-F11 -(Cmd-Shift-F11, on Mac) to run your currently visible application.
- -You've just completed your first Android application! Continue reading for an introduction -to debugging and a little more information on using other IDEs. Once you're ready to move on, -please begin by reading Application -Fundamentals. Also refer to the Developer's Guide -introduction page for an overview of the Dev Guide documentation.
- - -In Eclipse, open the file named R.java in your source code folder in the Package -Explorer. It should look something like this:
- -
-public final class R {
- public static final class attr {
- }
- public static final class drawable {
- public static final int icon=0x7f020000;
- }
- public static final class layout {
- public static final int main=0x7f030000;
- }
- public static final class string {
- public static final int app_name=0x7f040001;
- public static final int hello=0x7f040000;
- }
-}
-
-
-A project's R.java file is an index into all the resources defined in the -file. You use this class in your source code as a sort of short-hand -way to refer to resources you've included in your project. This is -particularly powerful with the code-completion features of IDEs like Eclipse -because it lets you quickly and interactively locate the specific reference -you're looking for.
- -It's possible yours looks slighly different than this (perhaps the hexadecimal values are different). -For now, notice the inner class named "layout", and its -member field "main". The Eclipse plugin noticed the XML -layout file named main.xml and generated a class for it here. As you add other -resources to your project (such as strings in the res/values/string.xml file or drawables inside -the res/drawable/ direcory) you'll see R.java change to keep up.
-When not using Eclipse, this class file will be generated for you at build time (with the Ant tool).
-You should never edit this file by hand.
-The Android Plugin for Eclipse also has excellent integration with the Eclipse -debugger. To demonstrate this, let's introduce a bug into -our code. Change your HelloAndroid source code to look like this:
- -
-package com.android.hello;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-public class HelloAndroid extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Object o = null;
- o.toString();
- setContentView(R.layout.main);
- }
-}
-
-This change simply introduces a NullPointerException into your code. If -you run your application again, you'll eventually see this:
- -
-
-Press "Force Quit" to terminate the application and close the emulator window.
- -To find out more about the error, set a breakpoint in your source code
-on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello,
-Android from the menu to enter debug mode. Your app will restart in the
-emulator, but this time it will suspend when it reaches the breakpoint you
-set. You can then step through the code in Eclipse's Debug Perspective,
-just as you would for any other application.
-
-
-If you don't use Eclipse (such as if you prefer another IDE, or simply use text - editors and command line tools) then the Eclipse plugin can't help you. - Don't worry though — you don't lose any functionality just because you don't - use Eclipse.
- -The Android Plugin for Eclipse is really just a wrapper around a set of tools - included with the Android SDK. (These tools, like the emulator, aapt, adb, - ddms, and others are documented elsewhere.) Thus, it's possible to - wrap those tools with another tool, such as an 'ant' build file.
- -The Android SDK includes a Python script named "activitycreator.py" that can be - used to create all the source code and directory stubs for your project, as well - as an ant-compatible build.xml file. This allows you to build your project - from the command line, or integrate it with the IDE of your choice.
- -For example, to create a HelloAndroid project similar to the one we just created - via Eclipse, you'd use this command:
- -activitycreator.py --out HelloAndroid com.android.hello.HelloAndroid- -
To build the project, you'd then run the command 'ant'. When that command - successfully completes, you'll be left with a file named HelloAndroid.apk under - the 'bin' directory. That .apk file is an Android Package, and can be - installed and run in your emulator using the 'adb' tool.
- -For more information on how to use these tools, please read the documentation - cited above.
diff --git a/docs/html/guide/tutorials/images/hello_world_0.png b/docs/html/guide/tutorials/images/hello_world_0.png deleted file mode 100644 index c174fba..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_0.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_1.png b/docs/html/guide/tutorials/images/hello_world_1.png deleted file mode 100644 index f08438a..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_1.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_2.png b/docs/html/guide/tutorials/images/hello_world_2.png deleted file mode 100644 index 58f5703..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_2.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_3.png b/docs/html/guide/tutorials/images/hello_world_3.png deleted file mode 100644 index d2d2ff6..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_3.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_4.png b/docs/html/guide/tutorials/images/hello_world_4.png deleted file mode 100644 index 5c41e80..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_4.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_5.png b/docs/html/guide/tutorials/images/hello_world_5.png deleted file mode 100644 index 96b830a..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_5.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_8.png b/docs/html/guide/tutorials/images/hello_world_8.png deleted file mode 100644 index 07db360..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_8.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_9.png b/docs/html/guide/tutorials/images/hello_world_9.png deleted file mode 100644 index e172e63..0000000 Binary files a/docs/html/guide/tutorials/images/hello_world_9.png and /dev/null differ diff --git a/docs/html/guide/tutorials/index.html b/docs/html/guide/tutorials/index.html deleted file mode 100644 index 4881acf..0000000 --- a/docs/html/guide/tutorials/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/tutorials/notepad/codelab/NotepadCodeLab.zip b/docs/html/guide/tutorials/notepad/codelab/NotepadCodeLab.zip deleted file mode 100644 index c7dd989..0000000 Binary files a/docs/html/guide/tutorials/notepad/codelab/NotepadCodeLab.zip and /dev/null differ diff --git a/docs/html/guide/tutorials/notepad/index.jd b/docs/html/guide/tutorials/notepad/index.jd deleted file mode 100644 index 6319fad..0000000 --- a/docs/html/guide/tutorials/notepad/index.jd +++ /dev/null @@ -1,142 +0,0 @@ -page.title=Notepad Tutorial -@jd:body - - -This tutorial on writing a notepad application gives you a "hands-on" introduction -to the Android framework and the tools you use to build applications on it. -Starting from a preconfigured project file, it guides you through the process of -developing a simple notepad application and provides concrete examples of how to -set up the project, develop the application logic and user interface, and then -compile and run the application.
- -The tutorial presents the application development as a set of -exercises (see below), each consisting of several steps. You should follow -the steps in each exercise to gradually build and refine your -application. The exercises explain each step in detail and provide all the -sample code you need to complete the application.
- -When you are finished with the tutorial, you will have created a functioning -Android application and will have learned many of the most important -concepts in Android development. If you want to add more complex features to -your application, you can examine the code in an alternative implementation -of a Note Pad application, in the -Sample Code section.
- - - -This tutorial is designed for experienced developers, especially those with -knowledge of the Java programming language. If you haven't written Java -applications before, you can still use the tutorial, but you might need to work -at a slower pace.
- -Also note that this tutorial uses -the Eclipse development environment, with the Android plugin installed. If you -are not using Eclipse, you can follow the exercises and build the application, -but you will need to determine how to accomplish the Eclipse-specific -steps in your environment.
- - -The tutorial assumes that you have some familiarity with basic Android -application concepts and terminology. If you are not, you -should read Application -Fundamentals before continuing.
- -This tutorial also builds on the introductory information provided in the -Hello World -tutorial, which explains how to set up your Eclipse environment -for building Android applications. We recommend you complete the Hello World -tutorial before starting this one.
- -To prepare for this lesson:
- -NotepadCodeLab folder.Inside the NotepadCodeLab folder, you should see six project
-files: Notepadv1,
- Notepadv2, Notepadv3,
- Notepadv1Solution, Notepadv2Solution
- and Notepadv3Solution. The Notepadv# projects are
-the starting points for each of the exercises, while the
-Notepadv#Solution projects are the exercise
- solutions. If you are having trouble with a particular exercise, you
- can compare your current work against the exercise solution.
The table below lists the tutorial exercises and describes the development -areas that each covers. Each exercise assumes that you have completed any -previous exercises.
- -| Exercise -1 | -Start here. Construct a simple notes list that lets the user add new notes but not
-edit them. Demonstrates the basics of ListActivity and creating
-and handling
- menu options. Uses a SQLite database to store the notes. |
-
|---|---|
| Exercise 2 | -Add a second Activity to the
-application. Demonstrates constructing a
-new Activity, adding it to the Android manifest, passing data between the
-activities, and using more advanced screen layout. Also shows how to
-invoke another Activity to return a result, using
-startActivityForResult(). |
-
| Exercise 3 | -Add handling of life-cycle events to -the application, to let it -maintain application state across the life cycle. | -
| Extra -Credit | -Demonstrates how to use the Eclipse -debugger and how you can use it to -view life-cycle events as they are generated. This section is optional but -highly recommended. | -
samples/ directory of your downloaded SDK, or browser them
-here, in the Sample Code section.samples/ directory of the SDK, though it does not match it exactly.
-When you are done with the tutorial,
-it is highly recommended that you take a closer look at this version of the Notepad
-application,
-as it demonstrates a variety of interesting additions for your application,
-such as:draw()
- method to make it look like a lined notepad.ContentProvider for notes.In this exercise, you will construct a simple notes list that lets the -user add new notes but not edit them. The exercise demonstrates:
-ListActivities and creating and handling menu
-options. Open up the Notepadv1 project in Eclipse.
Notepadv1 is a project that is provided as a starting point. It
- takes care of some of the boilerplate work that you have already seen if you
- followed the Hello,
- World tutorial.
NotepadCodeLab
- (downloaded during setup). Select
- Notepadv1 and click Choose.Notepadv1 in the Project name and also see the Location
- filled in with the path you selected.Notepadv1 project should open and be
- visible in your Eclipse package explorer.If you see an error about AndroidManifest.xml, or some
- problems related to an Android zip file, right click on the project and
- select Android Tools > Fix Project Properties.
- (The project is looking in the wrong location for the library file,
- this will fix it for you.)
For this - exercise, we are using a SQLite database to store our data. This is useful - if only your application will need to access or modify the data. If you wish for - other activities to access or modify the data, you have to expose the data using a - {@link android.content.ContentProvider ContentProvider}.
-If you are interested, you can find out more about
- content providers or the whole
- subject of Data Storage.
- The NotePad sample in the samples/ folder of the SDK also has an example of how
- to create a ContentProvider.
Take a look at the NotesDbAdapter class — this class is provided to
- encapsulate data access to a SQLite database that will hold our notes data
- and allow us to update it.
At the top of the class are some constant definitions that will be used in the application - to look up data from the proper field names in the database. There is also a database creation - string defined, which is used to create a new database schema if one doesn't exist already.
-Our database will have the name data, and have a single table called
- notes, which in turn has three fields: _id, title and
- body. The _id is named with an underscore convention used in a number of
- places inside the Android SDK and helps keep a track of state. The _id
- usually has to be specified when querying or updating the database (in the column projections
- and so on). The other two fields are simple text fields that will store data.
-
The constructor for NotesDbAdapter takes a Context, which allows it to communicate with aspects
- of the Android operating system. This is quite common for classes that need to touch the
- Android system in some way. The Activity class implements the Context class, so usually you will just pass
- this from your Activity, when needing a Context.
The open() method calls up an instance of DatabaseHelper, which is our local
- implementation of the SQLiteOpenHelper class. It calls getWritableDatabase(),
- which handles creating/opening a database for us.
close() just closes the database, releasing resources related to the
- connection.
createNote() takes strings for the title and body of a new note,
- then creates that note in the database. Assuming the new note is created successfully, the
- method also returns the row _id value for the newly created note.
deleteNote() takes a rowId for a particular note, and deletes that note from
- the database.
fetchAllNotes() issues a query to return a {@link android.database.Cursor} over all notes in the
- database. The query() call is worth examination and understanding. The first field is the
- name of the database table to query (in this case DATABASE_TABLE is "notes").
- The next is the list of columns we want returned, in this case we want the _id,
- title and body columns so these are specified in the String array.
- The remaining fields are, in order: selection,
- selectionArgs, groupBy, having and orderBy.
- Having these all null means we want all data, need no grouping, and will take the default
- order. See {@link android.database.sqlite.SQLiteDatabase SQLiteDatabase} for more details.
Note: A Cursor is returned rather than a collection of rows. This allows - Android to use resources efficiently -- instead of putting lots of data straight into memory - the cursor will retrieve and release data as it is needed, which is much more efficient for - tables with lots of rows.
- -fetchNote() is similar to fetchAllNotes() but just gets one note
- with the rowId we specify. It uses a slightly different version of the
- {@link android.database.sqlite.SQLiteDatabase} query() method.
- The first parameter (set true) indicates that we are interested
- in one distinct result. The selection parameter (the fourth parameter) has been specified to search
- only for the row "where _id =" the rowId we passed in. So we are returned a Cursor on
- the one row.
And finally, updateNote() takes a rowId, title and body, and uses a
- {@link android.content.ContentValues ContentValues} instance to update the note of the given
- rowId.
Most Activity classes will have a layout associated with them. The layout - will be the "face" of the Activity to the user. In this case our layout will - take over the whole screen and provide a list of notes.
-Full screen layouts are not the only option for an Activity however. You - might also want to use a floating - layout (for example, a dialog - or alert), - or perhaps you don't need a layout at all (the Activity will be invisible - to the user unless you specify some kind of layout for it to use).
-Open the notepad_list.xml file in res/layout
-and
- take a look at it. (You may have to
- hit the xml tab, at the bottom, in order to view the XML markup.)
This is a mostly-empty layout definition file. Here are some - things you should know about a layout file:
- - -<?xml version="1.0" encoding="utf-8"?>. LinearLayout. android: tags can
- be used through the rest of the file:
- xmlns:android="http://schemas.android.com/apk/res/android"
We need to create the layout to hold our list. Add code inside
- of the LinearLayout element so the whole file looks like this:
-<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="wrap_content" - android:layout_height="wrap_content"> - - <ListView android:id="@android:id/list" - android:layout_width="wrap_content" - android:layout_height="wrap_content"/> - <TextView android:id="@android:id/empty" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/no_notes"/> - -</LinearLayout> --
ListView and
- TextView tags means
- that the XML parser should parse and expand the rest of
- the id string and use an ID resource.ListView and TextView can be
- thought as two alternative views, only one of which will be displayed at once.
- ListView will be used when there are notes to be shown, while the TextView
- (which has a default value of "No Notes Yet!" defined as a string
- resource in res/values/strings.xml) will be displayed if there
- aren't any notes to display.list and empty IDs are
- provided for us by the Android platform, so, we must
- prefix the id with android: (e.g., @android:id/list).empty id is used
- automatically when the {@link android.widget.ListAdapter} has no data for the ListView. The
- ListAdapter knows to look for this name by default. Alternatively, you could change the
- default empty view by using {@link android.widget.AdapterView#setEmptyView(View)}
- on the ListView.
-
- More broadly, the android.R class is a set of predefined
- resources provided for you by the platform, while your project's
- R class is the set of resources your project has defined.
- Resources found in the android.R resource class can be
- used in the XML files by using the android: name space prefix
- (as we see here).
The folders under res/ in the Eclipse project are for resources. - There is a specific structure to the - folders and files under res/.
-Resources defined in these folders and files will have - corresponding entries in the R class allowing them to be easily accessed - and used from your application. The R class is automatically generated using the contents - of the res/ folder by the eclipse plugin (or by aapt if you use the command line tools). - Furthermore, they will be bundled and deployed for you as part of the application.
- -To make the list of notes in the ListView, we also need to define a View for each row:
-res/layout called
- notes_row.xml. -<?xml version="1.0" encoding="utf-8"?> -<TextView android:id="@+id/text1" - xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="wrap_content" - android:layout_height="wrap_content"/>-
- This is the View that will be used for each notes title row — it has only - one text field in it.
-In this case we create a new id called text1. The
- + after the @ in the id string indicates that the id should
- be automatically created as a resource if it does not already exist, so we are defining
- text1 on the fly and then using it.
Open the R.java class in the
- project and look at it, you should see new definitions for
- notes_row and text1 (our new definitions)
- meaning we can now gain access to these from the our code.
Next, open the Notepadv1 class in the source. In the following steps, we are going to
- alter this class to become a list adapter and display our notes, and also
- allow us to add new notes.
Notepadv1 will inherit from a subclass
- of Activity called a ListActivity,
- which has extra functionality to accommodate the kinds of
- things you might want to do with a list, for
- example: displaying an arbitrary number of list items in rows on the screen,
- moving through the list items, and allowing them to be selected.
Take a look through the existing code in Notepadv1 class.
- There is a currently an unused private field called mNoteNumber that
- we will use to create numbered note titles.
There are also three override methods defined:
- onCreate, onCreateOptionsMenu and
- onOptionsItemSelected; we need to fill these
- out:
onCreate() is called when the activity is
- started — it is a little like the "main" method for an Activity. We use
- this to set up resources and state for the activity when it is
- running.onCreateOptionsMenu() is used to populate the
- menu for the Activity. This is shown when the user hits the menu button,
-and
- has a list of options they can select (like "Create
- Note"). onOptionsItemSelected() is the other half of the
- menu equation, it is used to handle events generated from the menu (e.g.,
- when the user selects the "Create Note" item).
- Change the inheritance of Notepadv1 from
-Activity
- to ListActivity:
public class Notepadv1 extends ListActivity-
Note: you will have to import ListActivity into the
-Notepadv1
- class using Eclipse, ctrl-shift-O on Windows or Linux, or
- cmd-shift-O on the Mac (organize imports) will do this for you
- after you've written the above change.
Fill out the body of the onCreate() method.
Here we will set the title for the Activity (shown at the top of the
- screen), use the notepad_list layout we created in XML,
- set up the NotesDbAdapter instance that will
- access notes data, and populate the list with the available note
- titles:
onCreate method, call super.onCreate() with the
- savedInstanceState parameter that's passed in.setContentView() and pass R.layout.notepad_list.mDbHelper of class
- NotesDbAdapter.
- onCreate method, construct a new
-NotesDbAdapter
- instance and assign it to the mDbHelper field (pass
- this into the constructor for DBHelper)
- open() method on mDbHelper to open (or create) the
- database.
- fillData(), which will get the data and
- populate the ListView using the helper — we haven't defined this method yet.
- onCreate() should now look like this:
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.notepad_list);
- mDbHelper = new NotesDbAdapter(this);
- mDbHelper.open();
- fillData();
- }
- And be sure you have the mDbHelper field definition (right
- under the mNoteNumber definition):
private NotesDbAdapter mDbHelper;- -
The notepad application we are constructing only scratches the - surface with menus.
-You can also add -shortcut keys for menu items, create -submenus and even add -menu items to other applications!.
-Fill out the body of the onCreateOptionsMenu() method.
We will now create the "Add Item" button that can be accessed by pressing the menu -button on the device. We'll specify that it occupy the first position in the menu.
- -strings.xml resource (under res/values), add
- a new string named "menu_insert" with its value set to Add Item:
- <string name="menu_insert">Add Item</string>-
Then save the file and return to Notepadv1.
public static final int INSERT_ID = Menu.FIRST;-
onCreateOptionsMenu() method, change the
- super call so we capture the boolean return as result. We'll return this value at the end.menu.add().The whole method should now look like this: -
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- boolean result = super.onCreateOptionsMenu(menu);
- menu.add(0, INSERT_ID, 0, R.string.menu_insert);
- return result;
- }
- The arguments passed to add() indicate: a group identifier for this menu (none,
- in this case), a unique ID (defined above), the order of the item (zero indicates no preference),
- and the resource of the string to use for the item.
Fill out the body of the onOptionsItemSelected() method:
This is going
- to handle our new "Add Note" menu item. When this is selected, the
- onOptionsItemSelected() method will be called with the
- item.getId() set to INSERT_ID (the constant we
- used to identify the menu item). We can detect this, and take the
- appropriate actions:
super.onOptionsItemSelected(item) method call goes at the
- end of this method — we want to catch our events first! item.getItemId().
- In the case of INSERT_ID, call a new method, createNote(),
- and return true, because we have handled this event and do not want to
- propagate it through the system.
onOptionsItemSelected()
- method at the end.
- The whole onOptionsItemSelect() method should now look like
- this:
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case INSERT_ID:
- createNote();
- return true;
- }
-
- return super.onOptionsItemSelected(item);
- }
-
-Add a new createNote() method:
In this first version of
- our application, createNote() is not going to be very useful.
-We will simply
- create a new note with a title assigned to it based on a counter ("Note 1",
- "Note 2"...) and with an empty body. At present we have no way of editing
- the contents of a note, so for now we will have to be content making one
- with some default values:
- String noteName = "Note " + mNoteNumber++mDbHelper.createNote() using noteName as the
- title and "" for the body
- fillData() to populate the list of notes (inefficient but
- simple) — we'll create this method next.
- The whole createNote() method should look like this:
- private void createNote() {
- String noteName = "Note " + mNoteNumber++;
- mDbHelper.createNote(noteName, "");
- fillData();
- }
-
-
-Our example uses a {@link android.widget.SimpleCursorAdapter - SimpleCursorAdapter} to bind a database {@link android.database.Cursor Cursor} - into a ListView, and this is a common way to use a {@link android.widget.ListAdapter - ListAdapter}. Other options exist like {@link android.widget.ArrayAdapter ArrayAdapter} which - can be used to take a List or Array of in-memory data and bind it in to - a list as well.
-Define the fillData() method:
This
- method uses SimpleCursorAdapter, which takes a database Cursor
- and binds it to fields provided in the layout. These fields define the row elements of our list
- (in this case we use the text1 field in our
- notes_row.xml layout), so this allows us to easily populate the list with
- entries from our database.
To do this we have to provide a mapping from the title field in the returned Cursor, to
- our text1 TextView, which is done by defining two arrays: the first a string array
- with the list of columns to map from (just "title" in this case, from the constant
- NotesDbAdapter.KEY_TITLE) and, the second, an int array
- containing references to the views that we'll bind the data into
- (the R.id.text1 TextView).
This is a bigger chunk of code, so let's first take a look at it:
- -
- private void fillData() {
- // Get all of the notes from the database and create the item list
- Cursor c = mDbHelper.fetchAllNotes();
- startManagingCursor(c);
-
- String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
- int[] to = new int[] { R.id.text1 };
-
- // Now create an array adapter and set it to display using our row
- SimpleCursorAdapter notes =
- new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
- setListAdapter(notes);
- }
-
- Here's what we've done:
-mDbHelper.fetchAllNotes(), we
- use an Activity method called
- startManagingCursor() that allows Android to take care of the
- Cursor lifecycle instead of us needing to worry about it. (We will cover the implications
- of the lifecycle in exercise 3, but for now just know that this allows Android to do some
- of our resource management work for us.)this for the context (since subclasses of Activity
- implement Context). We pass the notes_row View we created as the receptacle
- for the data, the Cursor we just created, and then our arrays.
- In the future, remember that the mapping between the from columns and to resources
- is done using the respective ordering of the two arrays. If we had more columns we wanted
- to bind, and more Views to bind them in to, we would specify them in order, for example we
- might use { NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_BODY } and
- { R.id.text1, R.id.text2 } to bind two fields into the row (and we would also need
- to define text2 in the notes_row.xml, for the body text). This is how you can bind multiple fields
- into a single row (and get a custom row layout as well).
- If you get compiler errors about classes not being found, ctrl-shift-O or - (cmd-shift-O on the mac) to organize imports. -
- -Run it! -
Notepadv1 project.You can see the solution to this class in Notepadv1Solution
-from
-the zip file to compare with your own.
Once you are ready, move on to Tutorial -Exercise 2 to add the ability to create, edit and delete notes.
- diff --git a/docs/html/guide/tutorials/notepad/notepad-ex2.jd b/docs/html/guide/tutorials/notepad/notepad-ex2.jd deleted file mode 100644 index 3b8fa0b..0000000 --- a/docs/html/guide/tutorials/notepad/notepad-ex2.jd +++ /dev/null @@ -1,647 +0,0 @@ -page.title=Notepad Exercise 2 -parent.title=Notepad Tutorial -parent.link=index.html -@jd:body - - -In this exercise, you will add a second Activity to your notepad application, to let the user -create and edit notes. You will also allow the user to delete existing notes through a context menu. -The new Activity assumes responsibility for creating new notes by -collecting user input and packing it into a return Bundle provided by the intent. This exercise -demonstrates:
-startActivityForResult()Create a new Android project using the sources from Notepadv2 under the
-NotepadCodeLab folder, just like you did for the first exercise. If you see an error about
-AndroidManifest.xml, or some problems related to an
-android.zip file, right click on the project and select Android
-Tools > Fix Project Properties.
Open the Notepadv2 project and take a look around:
strings.xml file under
- res/values — there are several new strings which we will use
- for our new functionality
- Notepadv2 class,
- you will notice several new constants have been defined along with a new mNotesCursor
- field used to hold the cursor we are using.
- fillData() method has a few more comments and now uses
- the new field to store the notes Cursor. The onCreate() method is
- unchanged from the first exercise. Also notice that the member field used to store the
- notes Cursor is now called mNotesCursor. The m denotes a member
- field and is part of the Android coding style standards.
- onCreateContextMenu(), onContextItemSelected(),
- onListItemClick() and onActivityResult())
- which we will be filling in below.
- Context menus should always be used when performing actions upon specific elements in the UI. -When you register a View to a context menu, the context menu is revealed by performing a "long-click" -on the UI component (press and hold the touchscreen or highlight and hold down the selection key for about two seconds).
-First, let's create the context menu that will allow users to delete individual notes. -Open the Notepadv2 class.
- -registerForContextMenu() and pass it our ListView. So, at the very end of
- the onCreate() method add this line:
- registerForContextMenu(getListView());-
Because our Activity extends the ListActivity class, getListView() will return us
- the local ListView object for the Activity. Now, each list item in this ListView will activate the
- context menu.
-
onCreateContextMenu() method. This callback is similar to the other
- menu callback used for the options menu. Here, we add just one line, which will add a menu item
- to delete a note. Call menu.add() like so:
-
-public boolean onCreateContextMenu(Menu menu, View v
- ContextMenuInfo menuInfo) {
- super.onCreateContextMenu(menu, v, menuInfo);
- menu.add(0, DELETE_ID, 0, R.string.menu_delete);
-}
- The onCreateContextMenu() callback some passes other information in addition to the Menu object,
- such as the View that has been triggered for the menu and
- an extra object that may contain additional information about the object selected. However, we don't care about
- these here, because we only have one kind of object in the Activity that uses context menus. In the next
- step, we'll handle the menu item selection.
Now that the we've registered our ListView for a context menu and defined our context menu item, we need
- to handle the callback when it is selected. For this, we need to identify the list ID of the
- selected item, then delete it. So fill in the
- onContextItemSelected() method like this:
-public boolean onContextItemSelected(MenuItem item) {
- switch(item.getItemId()) {
- case DELETE_ID:
- AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
- mDbHelper.deleteNote(info.id);
- fillData();
- return true;
- }
- return super.onContextItemSelected(item);
-}
-Here, we retrieve the {@link android.widget.AdapterView.AdapterContextMenuInfo AdapterContextMenuInfo}
-with {@link android.view.MenuItem#getMenuInfo()}. The id field of this object tells us
-the position of the item in the ListView. We then pass this to the deleteNote()
-method of our NotesDbAdapter and the note is deleted. That's it for the context menu — notes
-can now be deleted.
In this example our Intent uses a class name specifically. - As well as - starting intents in - classes we already know about, be they in our own application or another - application, we can also create Intents without knowing exactly which - application will handle it.
-For example, we might want to open a page in a - browser, and for this we still use - an Intent. But instead of specifying a class to handle it, we use - a predefined Intent constant, and a content URI that describes what we - want to do. See {@link android.content.Intent - android.content.Intent} for more information.
-Fill in the body of the createNote() method:
-
Create a new Intent to create a note
- (ACTIVITY_CREATE) using the NoteEdit class.
- Then fire the Intent using the startActivityForResult() method
- call:
-Intent i = new Intent(this, NoteEdit.class); -startActivityForResult(i, ACTIVITY_CREATE);-
This form of the Intent call targets a specific class in our Activity, in this case
- NoteEdit. Since the Intent class will need to communicate with the Android
- operating system to route requests, we also have to provide a Context (this).
The startActivityForResult() method fires the Intent in a way that causes a method
- in our Activity to be called when the new Activity is completed. The method in our Activity
- that receives the callback is called
- onActivityResult() and we will implement it in a later step. The other way
- to call an Activity is using startActivity() but this is a "fire-and-forget" way
- of calling it — in this manner, our Activity is not informed when the Activity is completed, and there is
- no way to return result information from the called Activity with startActivity().
-
Don't worry about the fact that NoteEdit doesn't exist yet,
- we will fix that soon.
Fill in the body of the onListItemClick() override.
onListItemClick() is a callback method that we'll override. It is called when
- the user selects an item from the list. It is passed four parameters: the
- ListView object it was invoked from, the View
- inside the ListView that was clicked on, the
- position in the list that was clicked, and the
- mRowId of the item that was clicked. In this instance we can
- ignore the first two parameters (we only have one ListView it
- could be), and we ignore the mRowId as well. All we are
- interested in is the position that the user selected. We use
- this to get the data from the correct row, and bundle it up to send to
- the NoteEdit Activity.
In our implementation of the callback, the method creates an
- Intent to edit the note using
- the NoteEdit class. It then adds data into the extras Bundle of
- the Intent, which will be passed to the called Activity. We use it
- to pass in the title and body text, and the mRowId for the note we are
- editing. Finally, it will fire the Intent using the
- startActivityForResult() method call. Here's the code that
- belongs in onListItemClick():
-super.onListItemClick(l, v, position, id); -Cursor c = mNotesCursor; -c.moveToPosition(position); -Intent i = new Intent(this, NoteEdit.class); -i.putExtra(NotesDbAdapter.KEY_ROWID, id); -i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString( - c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE))); -i.putExtra(NotesDbAdapter.KEY_BODY, c.getString( - c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY))); -startActivityForResult(i, ACTIVITY_EDIT);-
putExtra() is the method to add items into the extras Bundle
- to pass in to intent invocations. Here, we are
- using the Bundle to pass in the title, body and mRowId of the note we want to edit.
- moveToPosition() method.NoteEdit class by passing startActivityForResult()
- the Intent and the request code. (The request code will be
- returned to onActivityResult as the requestCode parameter.)Note: We assign the mNotesCursor field to a local variable at the - start of the method. This is done as an optimization of the Android code. Accessing a local - variable is much more efficient than accessing a field in the Dalvik VM, so by doing this - we make only one access to the field, and five accesses to the local variable, making the - routine much more efficient. It is recommended that you use this optimization when possible.
- - -The above createNote() and onListItemClick()
- methods use an asynchronous Intent invocation. We need a handler for the callback, so here we fill
- in the body of the onActivityResult().
onActivityResult() is the overridden method
- which will be called when an Activity returns with a result. (Remember, an Activity
- will only return a result if launched with startActivityForResult.) The parameters provided
- to the callback are:
requestCode — the original request code
- specified in the Intent invocation (either ACTIVITY_CREATE or
- ACTIVITY_EDIT for us).
- resultCode — the result (or error code) of the call, this
- should be zero if everything was OK, but may have a non-zero code indicating
- that something failed. There are standard result codes available, and you
- can also create your own constants to indicate specific problems.
- intent — this is an Intent created by the Activity returning
- results. It can be used to return data in the Intent "extras."
- The combination of startActivityForResult() and
- onActivityResult() can be thought of as an asynchronous RPC
- (remote procedure call) and forms the recommended way for an Activity to invoke
- another and share services.
Here's the code that belongs in your onActivityResult():
-super.onActivityResult(requestCode, resultCode, intent);
-Bundle extras = intent.getExtras();
-
-switch(requestCode) {
-case ACTIVITY_CREATE:
- String title = extras.getString(NotesDbAdapter.KEY_TITLE);
- String body = extras.getString(NotesDbAdapter.KEY_BODY);
- mDbHelper.createNote(title, body);
- fillData();
- break;
-case ACTIVITY_EDIT:
- Long mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
- if (mRowId != null) {
- String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
- String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
- mDbHelper.updateNote(mRowId, editTitle, editBody);
- }
- fillData();
- break;
-}
-
- ACTIVITY_CREATE and
- ACTIVITY_EDIT activity results in this method.
- fillData() at the end ensures everything is up to date .
- The provided - note_edit.xml layout file is the most sophisticated one in the application we will be building, - but that doesn't mean it is even close to the kind of sophistication you will be likely to want - in real Android applications.
-Creating a - good UI is part art and part science, and the rest is work. Mastery of Declaring Layout is an essential part of creating - a good looking Android application.
-Take a look at the - Hello Views - for some example layouts and how to use them. The ApiDemos sample project is also a - great resource from which to learn how to create different layouts.
-Open the file note_edit.xml that has been provided and take a
- look at it. This is the UI code for the Note Editor.
This is the most - sophisticated UI we have dealt with yet. The file is given to you to avoid - problems that may sneak in when typing the code. (The XML is very strict - about case sensitivity and structure, mistakes in these are the usual cause - of problems with layout.)
-There is a new parameter used
- here that we haven't seen before: android:layout_weight (in
- this case set to use the value 1 in each case).
layout_weight is used in LinearLayouts
- to assign "importance" to Views within the layout. All Views have a default
- layout_weight of zero, meaning they take up only as much room
- on the screen as they need to be displayed. Assigning a value higher than
- zero will split up the rest of the available space in the parent View, according
- to the value of each View's layout_weight and its ratio to the
- overall layout_weight specified in the current layout for this
- and other View elements.
To give an example: let's say we have a text label
- and two text edit elements in a horizontal row. The label has no
- layout_weight specified, so it takes up the minimum space
- required to render. If the layout_weight of each of the two
- text edit elements is set to 1, the remaining width in the parent layout will
- be split equally between them (because we claim they are equally important).
- If the first one has a layout_weight of 1
- and the second has a layout_weight of 2, then one third of the
- remaining space will be given to the first, and two thirds to the
- second (because we claim the second one is more important).
This layout also demonstrates how to nest multiple layouts - inside each other to achieve a more complex and pleasant layout. In this - example, a horizontal linear layout is nested inside the vertical one to - allow the title label and text field to be alongside each other, - horizontally.
- - -Create a NoteEdit class that extends
- android.app.Activity.
This is the first time we will have
- created an Activity without the Android Eclipse plugin doing it for us. When
- you do so, the onCreate() method is not automatically
- overridden for you. It is hard to imagine an Activity that doesn't override
- the onCreate() method, so this should be the first thing you do.
com.android.demo.notepad2 package
- in the Package Explorer, and select New > Class from the popup
- menu.NoteEdit for the Name: field in the
- dialog.Superclass: field, enter
- android.app.Activity (you can also just type Activity and hit
- Ctrl-Space on Windows and Linux or Cmd-Space on the Mac, to invoke code
- assist and find the right package and class).NoteEdit class, right click in the editor
- window and select Source > Override/Implement Methods...onCreate(Bundle) — and check the box next to it.The method should now appear in your class.
Fill in the body of the onCreate() method for NoteEdit.
This will set the title of our new Activity to say "Edit Note" (one
- of the strings defined in strings.xml). It will also set the
- content view to use our note_edit.xml layout file. We can then
- grab handles to the title and body text edit views, and the confirm button,
- so that our class can use them to set and get the note title and body,
- and attach an event to the confirm button for when it is pressed by the
- user.
We can then unbundle the values that were passed in to the Activity
- with the extras Bundle attached to the calling Intent. We'll use them to pre-populate
- the title and body text edit views so that the user can edit them.
- Then we will grab and store the mRowId so we can keep
- track of what note the user is editing.
onCreate(), set up the layout:setContentView(R.layout.note_edit);-
These are found by the
- IDs associated to them in the R class, and need to be cast to the right
- type of View (EditText for the two text views,
- and Button for the confirm button):
-mTitleText = (EditText) findViewById(R.id.title); -mBodyText = (EditText) findViewById(R.id.body); -Button confirmButton = (Button) findViewById(R.id.confirm);-
Note that mTitleText and mBodyText are member
- fields (you need to declare them at the top of the class definition).
Long mRowId private field to store
- the current mRowId being edited (if any).
- onCreate(),
- add code to initialize the title, body and
- mRowId from the extras Bundle in
- the Intent (if it is present):
-mRowId = null;
-Bundle extras = getIntent().getExtras();
-if (extras != null) {
- String title = extras.getString(NotesDbAdapter.KEY_TITLE);
- String body = extras.getString(NotesDbAdapter.KEY_BODY);
- mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
-
- if (title != null) {
- mTitleText.setText(title);
- }
- if (body != null) {
- mBodyText.setText(body);
- }
-}
- title and
- body out of the
- extras Bundle that was set from the
- Intent invocation.
- onClickListener() for the button:
- Listeners can be one of the more confusing aspects of UI
- implementation, but
- what we are trying to achieve in this case is simple. We want an
- onClick() method to be called when the user presses the
- confirm button, and use that to do some work and return the values
- of the edited note to the Intent caller. We do this using something called
- an anonymous inner class. This is a bit confusing to look at unless you
- have seen them before, but all you really need to take away from this is
- that you can refer to this code in the future to see how to create a
- listener and attach it to a button. (Listeners are a common idiom
- in Java development, particularly for user interfaces.) Here's the empty listener:
-
-confirmButton.setOnClickListener(new View.OnClickListener() {
-
- public void onClick(View view) {
-
- }
-
-});
- Fill in the body of the onClick() method of the OnClickListener created in the last step.
This is the code that will be run when the user clicks on the
- confirm button. We want this to grab the title and body text from the edit
- text fields, and put them into the return Bundle so that they can be passed
- back to the Activity that invoked this NoteEdit Activity. If the
- operation is an edit rather than a create, we also want to put the
- mRowId into the Bundle so that the
- Notepadv2 class can save the changes back to the correct
- note.
Bundle and put the title and body text into it using the
- constants defined in Notepadv2 as keys:
-Bundle bundle = new Bundle();
-
-bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
-bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
-if (mRowId != null) {
- bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
-}
- -Intent mIntent = new Intent(); -mIntent.putExtras(bundle); -setResult(RESULT_OK, mIntent); -finish();-
setResult() method is used to set the result
- code and return Intent to be passed back to the
- Intent caller. In this case everything worked, so we return RESULT_OK for the
- result code.finish() call is used to signal that the Activity
- is done (like a return call). Anything set in the Result will then be
- returned to the caller, along with execution control.The full onCreate() method (plus supporting class fields) should
- now look like this:
-private EditText mTitleText;
-private EditText mBodyText;
-private Long mRowId;
-
-@Override
-protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.note_edit);
-
- mTitleText = (EditText) findViewById(R.id.title);
- mBodyText = (EditText) findViewById(R.id.body);
-
- Button confirmButton = (Button) findViewById(R.id.confirm);
-
- mRowId = null;
- Bundle extras = getIntent().getExtras();
- if (extras != null) {
- String title = extras.getString(NotesDbAdapter.KEY_TITLE);
- String body = extras.getString(NotesDbAdapter.KEY_BODY);
- mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
-
- if (title != null) {
- mTitleText.setText(title);
- }
- if (body != null) {
- mBodyText.setText(body);
- }
- }
-
- confirmButton.setOnClickListener(new View.OnClickListener() {
-
- public void onClick(View view) {
- Bundle bundle = new Bundle();
-
- bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
- bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
- if (mRowId != null) {
- bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
- }
-
- Intent mIntent = new Intent();
- mIntent.putExtras(bundle);
- setResult(RESULT_OK, mIntent);
- finish();
- }
- });
-}
-
-
-
-The AndroidManifest.xml file is the way in which Android sees your - application. This file defines the category of the application, where - it shows up (or even if it shows up) in the launcher or settings, what - activities, services, and content providers it defines, what intents it can - receive, and more.
-For more information, see the reference document - The AndroidManifest.xml File
-Finally, the new Activity has to be defined in the manifest file:
-Before the new Activity can be seen by Android, it needs its own
- Activity entry in the AndroidManifest.xml file. This is to let
- the system know that it is there and can be called. We could also specify
- which IntentFilters the activity implements here, but we are going to skip
- this for now and just let Android know that the Activity is
- defined.
There is a Manifest editor included in the Eclipse plugin that makes it much easier - to edit the AndroidManifest file, and we will use this. If you prefer to edit the file directly - or are not using the Eclipse plugin, see the box at the end for information on how to do this - without using the new Manifest editor.
-
AndroidManifest.xml file in the package explorer to open it.
- If you see a dialog with radiobuttons at the top, select the top radio button: - "Create a new element at the top level, in Application".
.NoteEdit into the Name*
- field to the right. Press Return/Enter.The Android Manifest editor helps you add more complex entries into the AndroidManifest.xml - file, have a look around at some of the other options available (but be careful not to select - them otherwise they will be added to your Manifest). This editor should help you understand - and alter the AndroidManifest.xml file as you move on to more advanced Android applications.
- -If you prefer to edit this file directly, simply open the
- AndroidManifest.xml file and look at the source (use the
- AndroidManifest.xml tab in the eclipse editor to see the source code directly).
- Then edit the file as follows:
- <activity android:name=".NoteEdit"></activity>
- This should be placed just below the line that reads:
- </activity> for the .Notepadv2 activity.
Now Run it!
-You should now be able to add real notes from -the menu, as well as delete an existing one. Notice that in order to delete, you must -first use the directional controls on the device to highlight the note. -Furthermore, selecting a note title from the list should bring up the note -editor to let you edit it. Press confirm when finished to save the changes -back to the database. - -
You can see the solution to this exercise in Notepadv2Solution
-from the zip file to compare with your own.
Now try editing a note, and then hitting the back button on the emulator -instead of the confirm button (the back button is below the menu button). You -will see an error come up. Clearly our application still has some problems. -Worse still, if you did make some changes and hit the back button, when you go -back into the notepad to look at the note you changed, you will find that all -your changes have been lost. In the next exercise we will fix these -problems.
- --Once you are ready, move on to Tutorial -Exercise 3 where you will fix the problems with the back button and lost -edits by introducing a proper life cycle into the NoteEdit Activity.
- - diff --git a/docs/html/guide/tutorials/notepad/notepad-ex3.jd b/docs/html/guide/tutorials/notepad/notepad-ex3.jd deleted file mode 100644 index 8737280..0000000 --- a/docs/html/guide/tutorials/notepad/notepad-ex3.jd +++ /dev/null @@ -1,358 +0,0 @@ -page.title=Notepad Exercise 3 -parent.title=Notepad Tutorial -parent.link=index.html -@jd:body - - -In this exercise, you will use life-cycle event callbacks to store and -retrieve application state data. This exercise demonstrates:
-Import Notepadv3 into Eclipse. If you see an error about
-AndroidManifest.xml, or some problems related to an Android zip
-file, right click on the project and select Android Tools >
-Fix Project Properties from the popup menu. The starting point for this exercise is
-exactly where we left off at the end of the Notepadv2.
The current application has some problems — hitting the back button when editing -causes a crash, and anything else that happens during editing will cause the -edits to be lost.
-To fix this, we will move most of the functionality for creating and editing -the note into the NoteEdit class, and introduce a full life cycle for editing -notes.
- -NoteEdit that parses the title and body
- from the extras Bundle.
- Instead, we are going to use the DBHelper class
- to access the notes from the database directly. All we need passed into the
- NoteEdit Activity is a mRowId (but only if we are editing, if creating we pass
- nothing). Remove these lines:
-String title = extras.getString(NotesDbAdapter.KEY_TITLE); -String body = extras.getString(NotesDbAdapter.KEY_BODY);-
extras Bundle, which we were using to set the title
- and body text edit values in the UI. So delete:
-
-if (title != null) {
- mTitleText.setText(title);
-}
-if (body != null) {
- mBodyText.setText(body);
-}
- Create a class field for a NotesDbAdapter at the top of the NoteEdit class:
private NotesDbAdapter mDbHelper;-
Also add an instance of NotesDbAdapter in the
- onCreate() method (right below the super.onCreate() call):
- mDbHelper = new NotesDbAdapter(this);- -
- mDbHelper.open();
In NoteEdit, we need to check the savedInstanceState for the
-mRowId, in case the note
- editing contains a saved state in the Bundle, which we should recover (this would happen
- if our Activity lost focus and then restarted).
mRowId:
- mRowId = null;
-
- Bundle extras = getIntent().getExtras();
- if (extras != null) {
- mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
- }
-
- with this:
-
- mRowId = savedInstanceState != null ? savedInstanceState.getLong(NotesDbAdapter.KEY_ROWID)
- : null;
- if (mRowId == null) {
- Bundle extras = getIntent().getExtras();
- mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
- : null;
- }
-
- savedInstanceState, and we still need to load up
- mRowId from the extras Bundle if it is not
- provided by the savedInstanceState. This is a ternary operator shorthand
- to safely either use the value or null if it is not present.
- Next, we need to populate the fields based on the mRowId if we
- have it:
populateFields();-
This goes before the confirmButton.setOnClickListener() line.
- We'll define this method in a moment.
Get rid of the Bundle creation and Bundle value settings from the
- onClick() handler method. The Activity no longer needs to
- return any extra information to the caller. And because we no longer have
- an Intent to return, we'll use the shorter version
- of setResult():
-public void onClick(View view) {
- setResult(RESULT_OK);
- finish();
-}
- We will take care of storing the updates or new notes in the database - ourselves, using the life-cycle methods.
- -The whole onCreate() method should now look like this:
-super.onCreate(savedInstanceState);
-
-mDbHelper = new NotesDbAdapter(this);
-mDbHelper.open();
-
-setContentView(R.layout.note_edit);
-
-mTitleText = (EditText) findViewById(R.id.title);
-mBodyText = (EditText) findViewById(R.id.body);
-
-Button confirmButton = (Button) findViewById(R.id.confirm);
-
-mRowId = savedInstanceState != null ? savedInstanceState.getLong(NotesDbAdapter.KEY_ROWID)
- : null;
-if (mRowId == null) {
- Bundle extras = getIntent().getExtras();
- mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
- : null;
-}
-
-populateFields();
-
-confirmButton.setOnClickListener(new View.OnClickListener() {
-
- public void onClick(View view) {
- setResult(RESULT_OK);
- finish();
- }
-
-});
-
-Define the populateFields() method.
-private void populateFields() {
- if (mRowId != null) {
- Cursor note = mDbHelper.fetchNote(mRowId);
- startManagingCursor(note);
- mTitleText.setText(note.getString(
- note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
- mBodyText.setText(note.getString(
- note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
- }
-}
-This method uses the NotesDbAdapter.fetchNote() method to find the right note to
-edit, then it calls startManagingCursor() from the Activity class, which
-is an Android convenience method provided to take care of the Cursor life-cycle. This will release
-and re-create resources as dictated by the Activity life-cycle, so we don't need to worry about
-doing that ourselves. After that, we just look up the title and body values from the Cursor
-and populate the View elements with them.
If you are used to always having control in your applications, you - might not understand why all this life-cycle work is necessary. The reason - is that in Android, you are not in control of your Activity, the - operating system is!
-As we have already seen, the Android model is based around activities - calling each other. When one Activity calls another, the current Activity - is paused at the very least, and may be killed altogether if the - system starts to run low on resources. If this happens, your Activity will - have to store enough state to come back up later, preferably in the same - state it was in when it was killed.
-- Android has a well-defined life cycle. - Lifecycle events can happen even if you are not handing off control to - another Activity explicitly. For example, perhaps a call comes in to the - handset. If this happens, and your Activity is running, it will be swapped - out while the call Activity takes over.
-Still in the NoteEdit class, we now override the methods
- onSaveInstanceState(), onPause() and
- onResume(). These are our life-cycle methods
- (along with onCreate() which we already have).
onSaveInstanceState() is called by Android if the
- Activity is being stopped and may be killed before it is
- resumed! This means it should store any state necessary to
- re-initialize to the same condition when the Activity is restarted. It is
- the counterpart to the onCreate() method, and in fact the
- savedInstanceState Bundle passed in to onCreate() is the same
- Bundle that you construct as outState in the
- onSaveInstanceState() method.
onPause() and onResume() are also
- complimentary methods. onPause() is always called when the
- Activity ends, even if we instigated that (with a finish() call for example).
- We will use this to save the current note back to the database. Good
- practice is to release any resources that can be released during an
- onPause() as well, to take up less resources when in the
- passive state. onResume() will call our populateFields() method
- to read the note out of the database again and populate the fields.
So, add some space after the populateFields() method
- and add the following life-cycle methods:
- onSaveInstanceState():
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
- }
-
- onPause():
-
- @Override
- protected void onPause() {
- super.onPause();
- saveState();
- }
- We'll define saveState() next.
- onResume():
-
- @Override
- protected void onResume() {
- super.onResume();
- populateFields();
- }
- Define the saveState() method to put the data out to the
-database.
- private void saveState() {
- String title = mTitleText.getText().toString();
- String body = mBodyText.getText().toString();
-
- if (mRowId == null) {
- long id = mDbHelper.createNote(title, body);
- if (id > 0) {
- mRowId = id;
- }
- } else {
- mDbHelper.updateNote(mRowId, title, body);
- }
- }
- Note that we capture the return value from createNote() and if a valid row ID is
- returned, we store it in the mRowId field so that we can update the note in future
- rather than create a new one (which otherwise might happen if the life-cycle events are
- triggered).
Now pull out the previous handling code from the
- onActivityResult() method in the Notepadv3
- class.
All of the note retrieval and updating now happens within the
- NoteEdit life cycle, so all the onActivityResult()
- method needs to do is update its view of the data, no other work is
- necessary. The resulting method should look like this:
-@Override
-protected void onActivityResult(int requestCode, int resultCode,
- Intent intent) {
- super.onActivityResult(requestCode, resultCode, intent);
- fillData();
-}
-
-Because the other class now does the work, all this has to do is refresh - the data.
- -Also remove the lines which set the title and body from the
- onListItemClick() method (again they are no longer needed,
- only the mRowId is):
- Cursor c = mNotesCursor; - c.moveToPosition(position);-
- i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString( - c.getColumnIndex(NotesDbAdapter.KEY_TITLE))); - i.putExtra(NotesDbAdapter.KEY_BODY, c.getString( - c.getColumnIndex(NotesDbAdapter.KEY_BODY)));-
- super.onListItemClick(l, v, position, id); - Intent i = new Intent(this, NoteEdit.class); - i.putExtra(NotesDbAdapter.KEY_ROWID, id); - startActivityForResult(i, ACTIVITY_EDIT);- -
You can also now remove the mNotesCursor field from the class, and set it back to using
- a local variable in the fillData() method:
-
- Cursor notesCursor = mDbHelper.fetchAllNotes();-
Note that the m in mNotesCursor denotes a member field, so when we
- make notesCursor a local variable, we drop the m. Remember to rename the
- other occurrences of mNotesCursor in your fillData() method.
-
-
-Run it! (use Run As -> Android Application on the project right -click menu again)
- -You can see the solution to this exercise in Notepadv3Solution
-from
-the zip file to compare with your own.
-When you are ready, move on to the Tutorial -Extra Credit exercise, where you can use the Eclipse debugger to -examine the life-cycle events as they happen.
diff --git a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd b/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd deleted file mode 100644 index 0d59b56..0000000 --- a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd +++ /dev/null @@ -1,70 +0,0 @@ -page.title=Notepad Extra Credit -parent.title=Notepad Tutorial -parent.link=index.html -@jd:body - - -In this exercise, you will use the debugger to look at the work you did -in Exercise 3. This exercise demonstrates:
-Using the working Notepadv3, put breakpoints in the code at the
- beginning of the onCreate(), onPause(),
- onSaveInstanceState() and onResume() methods in the
- NoteEdit class (if you are not familiar with Eclipse, just
- right click in the narrow grey border on the left of the edit window at the
- line you want a breakpoint, and select Toggle Breakpoint, you
-should see a blue dot appear).
Now start the notepad demo in debug mode:
- -Notepadv3 project and from the Debug menu
- select Debug As -> Android Application.adb kill-server, and then restart
-Eclipse and try again.When you edit or create a new note you should see the breakpoints getting - hit and the execution stopping.
- -Hit the Resume button to let execution continue (yellow rectangle with a -green triangle to its right in the Eclipse toolbars near the top).
- -Experiment a bit with the confirm and back buttons, and try pressing Home and - making other mode changes. Watch what life-cycle events are generated and -when.
- -The Android Eclipse plugin not only offers excellent debugging support for -your application development, but also superb profiling support. You can also -try using Traceview to profile your application. If your application is running too slow, this can help you -find the bottlenecks and fix them.
- diff --git a/docs/html/guide/tutorials/notepad/notepad-index.jd b/docs/html/guide/tutorials/notepad/notepad-index.jd deleted file mode 100644 index 151c50d..0000000 --- a/docs/html/guide/tutorials/notepad/notepad-index.jd +++ /dev/null @@ -1,143 +0,0 @@ -page.title=Notepad Tutorial -@jd:body - - -The tutorial in this section gives you a "hands-on" introduction -to the Android framework and the tools you use to build applications on it. -Starting from a preconfigured project file, it guides you through the process of -developing a simple notepad application and provides concrete examples of how to -set up the project, develop the application logic and user interface, and then -compile and run the application.
- -The tutorial presents the notepad application development as a set of -exercises (see below), each consisting of several steps. You can follow along -with the steps in each exercise and gradually build up and refine your -application. The exercises explain each step in detail and provide all the -sample code you need to complete the application.
- -When you are finished with the tutorial, you will have created a functioning -Android application and learned in depth about many of the most important -concepts in Android development. If you want to add more complex features to -your application, you can examine the code in an alternative implementation -of a notepad application, in the -Sample Code documentation.
- - - -This tutorial is designed for experienced developers, especially those with -knowledge of the Java programming language. If you haven't written Java -applications before, you can still use the tutorial, but you might need to work -at a slower pace.
- -The tutorial assumes that you have some familiarity with the basic Android -application concepts and terminology. If you aren't yet familiar with those, you -should read Overview of an Android -Application before continuing.
- -Also note that this tutorial uses -the Eclipse development environment, with the Android plugin installed. If you -are not using Eclipse, you can follow the exercises and build the application, -but you will need to determine how to accomplish the Eclipse-specific -steps in your environment.
- - -This tutorial builds on the information provided in the Installing the SDK and Hello Android -documents, which explain in detail how to set up your development environment -for building Android applications. Before you start this tutorial, you should -read both these documents, have the SDK installed, and your work environment set up.
- -To prepare for this lesson:
- -NotepadCodeLab folderInside the NotepadCodeLab folder, you should see six project
-files: Notepadv1,
- Notepadv2, Notepadv3,
- Notepadv1Solution, Notepadv2Solution
- and Notepadv3Solution. The Notepadv# projects are
-the starting points for each of the exercises, while the
-Notepadv#Solution projects are the exercise
- solutions. If you are having trouble with a particular exercise, you
- can compare your current work against the exercise solution.
The table below lists the tutorial exercises and describes the development -areas that each covers. Each exercise assumes that you have completed any -previous exercises.
- -| Exercise -1 | -Start here. Construct a simple notes list that lets the user add new notes but not
-edit them. Demonstrates the basics of ListActivity and creating
-and handling
- menu options. Uses a SQLite database to store the notes. |
-
|---|---|
| Exercise 2 | -Add a second Activity to the
-application. Demonstrates constructing a
-new Activity, adding it to the Android manifest, passing data between the
-activities, and using more advanced screen layout. Also shows how to
-invoke another Activity to return a result, using
-startActivityForResult(). |
-
| Exercise 3 | -Add handling of life-cycle events to -the application, to let it -maintain application state across the life cycle. | -
| Extra -Credit | -Demonstrates how to use the Eclipse -debugger and how you can use it to -view life-cycle events as they are generated. This section is optional but -highly recommended. | -
samples/ directory of your downloaded SDK.samples/ directory of the SDK, though it does not match it exactly.
-When you are done with the tutorial,
-it is highly recommended that you take a closer look at this version of the Notepad
-application,
-as it demonstrates a variety of interesting additions for your application,
-such as:draw()
-method to
- make it look like a lined notepad.ContentProvider for notes.{@link android.widget.AutoCompleteTextView} is an implementation of the EditText widget that will provide -auto-complete suggestions as the user types. The suggestions are extracted from a collection of strings.
- - --<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:orientation="horizontal" - android:layout_width="fill_parent" - android:layout_height="wrap_content"> - - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Country" /> - - <AutoCompleteTextView android:id="@+id/edit" - android:layout_width="fill_parent" - android:layout_height="wrap_content"/> - -</LinearLayout> --
onCreate method:
-
-@Override
-protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
- ArrayAdapter adapter = new ArrayAdapter(this,
- android.R.layout.simple_dropdown_item_1line, R.array.planets);
- textView.setAdapter(adapter);
-}
-
- Here, we create an AutoComplteteTextView from our layout. We then
- create an {@link android.widget.ArrayAdapter} that binds a simple_dropdown_item_1line
- layout item to each entry in the COUNTRIES array (which we'll add next).
- The last part sets the ArrayAdapter to associate with our AutoCompleteTextView.
onCreate() method, add the String array:
-
-static final String[] COUNTRIES = new String[] {
- "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
- "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
- "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
- "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
- "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
- "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
- "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
- "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
- "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
- "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
- "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
- "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
- "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
- "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
- "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
- "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
- "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
- "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
- "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
- "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
- "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
- "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
- "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
- "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
- "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
- "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
- "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
- "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
- "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
- "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
- "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
- "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
- "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
- "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
- "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
- "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
- "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
- "Ukraine", "United Arab Emirates", "United Kingdom",
- "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
- "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
- "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
-};
-
- This is the list of suggestions that will be offered as the user types into the - AutoCompleteTextView.
-As you type, you should see something like this:
-
-
-
-A {@link android.widget.DatePicker} is a widget that allows the user to select a month, day and year.
- - --<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:orientation="vertical"> - - <TextView android:id="@+id/dateDisplay" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text=""/> - - <Button android:id="@+id/pickDate" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Change the date"/> - -</LinearLayout> --
For the layout, we're using a vertical LinearLayout, with a {@link android.widget.TextView} that - will display the date and a {@link android.widget.Button} that will initiate the DatePicker dialog. - With this layout, the TextView will sit above the Button. - The text value in the TextView is set empty, as it will be filled - with the current date when our Activity runs.
-
- private TextView mDateDisplay;
- private Button mPickDate;
-
- private int mYear;
- private int mMonth;
- private int mDay;
-
- static final int DATE_DIALOG_ID = 0;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- // capture our View elements
- mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
- mPickDate = (Button) findViewById(R.id.pickDate);
-
- // add a click listener to the button
- mPickDate.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- showDialog(DATE_DIALOG_ID);
- }
- });
-
- // get the current date
- final Calendar c = Calendar.getInstance();
- mYear = c.get(Calendar.YEAR);
- mMonth = c.get(Calendar.MONTH);
- mDay = c.get(Calendar.DAY_OF_MONTH);
-
- // display the current date
- updateDisplay();
- }
-
-Tip: Press Ctrl(or Cmd) + Shift + O to import all needed packages.
-We start by instantiating variables for our Views and date fields.
- The DATE_DIALOG_ID is a static integer that uniquely identifies the Dialog. In the
- onCreate() method, we get prepared by setting the layout and capturing the View elements.
- Then we create an on-click listener for the Button, so that when it is clicked it will
- show our DatePicker dialog. The showDialog() method will pop-up the date picker dialog
- by calling the onCreateDialog() callback method
- (which we'll define in the next section). We then create an
- instance of {@link java.util.Calendar} and get the current year, month and day. Finally, we call
- updateDisplay()—our own method (defined later) that will fill the TextView.
onCreate() method, add the onCreateDialog() callback method
-(which is called by showDialog())
-
-@Override
-protected Dialog onCreateDialog(int id) {
- switch (id) {
- case DATE_DIALOG_ID:
- return new DatePickerDialog(this,
- mDateSetListener,
- mYear, mMonth, mDay);
- }
- return null;
-}
-
- This method is passed the identifier we gave showDialog() and initializes
- the DatePicker to the date we retrieved from our Calendar instance.
updateDisplay() method:
-
- // updates the date we display in the TextView
- private void updateDisplay() {
- mDateDisplay.setText(
- new StringBuilder()
- // Month is 0 based so add 1
- .append(mMonth + 1).append("-")
- .append(mDay).append("-")
- .append(mYear).append(" "));
- }
-
-This uses the member date values to write the date to our TextView.
-
- // the callback received when the user "sets" the date in the dialog
- private DatePickerDialog.OnDateSetListener mDateSetListener =
- new DatePickerDialog.OnDateSetListener() {
-
- public void onDateSet(DatePicker view, int year,
- int monthOfYear, int dayOfMonth) {
- mYear = year;
- mMonth = monthOfYear;
- mDay = dayOfMonth;
- updateDisplay();
- }
- };
-
- This OnDateSetListener method listens for when the user is done setting the date
- (clicks the "Set" button). At that time, this fires and we update our member fields with
- the new date defined by the user and update our TextView by calling updateDisplay().
When you press the "Change the date" button, you should see the following:
-
-
-This page introduces a variety of widgets, like image buttons, -text fields, checkboxes and radio buttons.
- - --<?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" > - -</LinearLayout> --
For each widget you want to add, just put the respective View inside here.
-Tip: As you add new Android code, press Ctrl(or Cmd) + Shift + O -to import all needed packages.
- - -A button with a custom image on it. -We'll make it display a message when pressed.
-
- Drag the Android image on the right (or your own image) into the
- res/drawables/ directory of your project.
- We'll use this for the button.-<ImageButton - android:id="@+id/android_button" - android:layout_width="100dip" - android:layout_height="wrap_content" - android:src="@drawable/android" /> --
The source of the button - is from the res/drawables/ directory, where we've placed the android.png.
-Tip: You can also reference some of the many built-in
- images from the Android {@link android.R.drawable} resources,
- like ic_media_play, for a "play" button image. To do so, change the source
- attribute to android:src="@android:drawable/ic_media_play".
onCreate() method:
-
-ImageButton button = (ImageButton) findViewById(R.id.android_button);
-button.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- // Perform action on clicks
- Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
- }
-});
-
-This captures our ImageButton from the layout, then adds an on-click listener to it.
-The {@link android.view.View.OnClickListener} must define the onClick() method, which
-defines the action to be made when the button is clicked. Here, we show a
-{@link android.widget.Toast} message when clicked.
A text field for user input. We'll make it display the text entered so far when the "Enter" key is pressed.
- --<EditText - android:id="@+id/edittext" - android:layout_width="fill_parent" - android:layout_height="wrap_content"/> --
onCreate() method:
-
-EditText edittext = (EditText) findViewById(R.id.edittext);
-edittext.setOnKeyListener(new OnKeyListener() {
- public boolean onKey(View v, int keyCode, KeyEvent event) {
- if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
- // Perform action on key press
- Toast.makeText(HelloImageButton.this, edittext.getText(), Toast.LENGTH_SHORT).show();
- return true;
- }
- return false;
- }
-});
-
-This captures our EditText element from the layout, then adds an on-key listener to it.
-The {@link android.view.View.OnKeyListener} must define the onKey() method, which
-defines the action to be made when a key is pressed. In this case, we want to listen for the
-Enter key (when pressed down), then pop up a {@link android.widget.Toast} message with the
-text from the EditText field. Be sure to return true after the event is handled,
-so that the event doesn't bubble-up and get handled by the View (which would result in a
-carriage return in the text field).
A checkbox for selecting items. We'll make it display the the current state when pressed.
- --<CheckBox android:id="@+id/checkbox" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="check it out" /> --
onCreate() method:
-
-final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
-checkbox.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- // Perform action on clicks
- if (checkbox.isChecked()) {
- Toast.makeText(HelloImageButton.this, "Selected", Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(HelloImageButton.this, "Not selected", Toast.LENGTH_SHORT).show();
- }
- }
-});
-
-This captures our CheckBox element from the layout, then adds an on-click listener to it.
-The {@link android.view.View.OnClickListener} must define the onClick() method, which
-defines the action to be made when the checkbox is clicked. Here, we query the current state of the
-checkbox, then pop up a {@link android.widget.Toast} message that displays the current state.
-Notice that the CheckBox handles its own state change between checked and un-checked, so we just
-ask which it currently is.
Tip: If you find that you need to change the state
-in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}),
-use setChecked(true) or toggle().
Two mutually-exclusive radio buttons—enabling one disables the other. -When each is pressed, we'll pop up a message.
- --<RadioGroup - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:orientation="vertical"> - - <RadioButton android:id="@+id/radio_red" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Red" /> - - <RadioButton android:id="@+id/radio_blue" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Blue" /> - -</RadioGroup> --
onCreate() method):
-
-OnClickListener radio_listener = new OnClickListener() {
- public void onClick(View v) {
- // Perform action on clicks
- RadioButton rb = (RadioButton) v;
- Toast.makeText(HelloImageButton.this, rb.getText(), Toast.LENGTH_SHORT).show();
- }
-};
-
-Our onClick() method will be handed the View clicked, so the first thing to do
-is cast it into a RadioButton. Then we pop up a
-{@link android.widget.Toast} message that displays the selection.
onCreate() method, add the following:
-- final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red); - final RadioButton radio_blue = (RadioButton) findViewById(R.id.radio_blue); - radio_red.setOnClickListener(radio_listener); - radio_blue.setOnClickListener(radio_listener); --
This captures each of the RadioButtons from our layout and adds the newly-created -OnClickListener to each.
-Tip: If you find that you need to change the state of a
-RadioButton in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}),
-use setChecked(true) or toggle().
A button used specifically for toggling something on and off.
- --<ToggleButton android:id="@+id/togglebutton" - android:layout_width="wrap_content" - android:layout_height="wrap_content" /> --
onCreate() method:
-
-final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
-togglebutton.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- // Perform action on clicks
- if (togglebutton.isChecked()) {
- Toast.makeText(HelloImageButton.this, "ON", Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(HelloImageButton.this, "OFF", Toast.LENGTH_SHORT).show();
- }
- }
-});
-
-This captures our ToggleButton element from the layout, then adds an on-click listener to it.
-The {@link android.view.View.OnClickListener} must define the onClick() method, which
-defines the action to be made when the button is clicked. Here, we query the current state of the
-ToggleButton, then pop up a {@link android.widget.Toast} message that displays the current state.
-Notice that the ToggleButton handles its own state change between checked and un-checked, so we just
-ask which it is.
Tip: By default, the text on the button is "ON" and "OFF", but
-you can change each of these with setTextOn(CharSequence) and
-setTextOff(CharSequence). And, if you find that you need to change the state
-in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}),
-use setChecked(true) or toggle().
If you've added all the form items above, your application should look something like this:
-
-
-A {@link android.widget.Gallery} is a View commonly used to display items in a horizontally scrolling list -that locks the current selection at the center. When one is selected, we'll show a message.
- - --<?xml version="1.0" encoding="utf-8"?> -<Gallery xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/gallery" - android:layout_width="fill_parent" - android:layout_height="wrap_content" -/> --
onCreate() method:
-
-@Override
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- Gallery g = (Gallery) findViewById(R.id.gallery);
- g.setAdapter(new ImageAdapter(this));
-
- g.setOnItemClickListener(new OnItemClickListener() {
- public void onItemClick(AdapterView parent, View v, int position, long id) {
- Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
- }
- });
-}
-
- We start as usual: set the layout and capture the View we want (our Gallery).
-We then set an Adapter, called ImageAdapter for the Gallery—this is a new class that
-we'll create next. Then we create an item click listener for the Gallery. This is like a normal
-on-click listener (which you might be familiar with for buttons), but it listens to each item
-that we've added to the Gallery. The onItemClick() callback method
-receives the AdapterView where the click occurred, the specific View that received the click, the
-position of the View clicked (zero-based), and the row id of the item clicked (if applicable). All
-that we care about is the position, so that we can pop up a {@link android.widget.Toast} message that
-tells us the index position of the item clicked. We do this with Toast.makeText().show().
-
onCreate() method, add the ImageAdapter class:
-
-public class ImageAdapter extends BaseAdapter {
- int mGalleryItemBackground;
- private Context mContext;
-
- private Integer[] mImageIds = {
- R.drawable.sample_1,
- R.drawable.sample_2,
- R.drawable.sample_3,
- R.drawable.sample_4,
- R.drawable.sample_5,
- R.drawable.sample_6,
- R.drawable.sample_7
- };
-
- public ImageAdapter(Context c) {
- mContext = c;
- TypedArray a = obtainStyledAttributes(android.R.styleable.Theme);
- mGalleryItemBackground = a.getResourceId(
- android.R.styleable.Theme_galleryItemBackground, 0);
- a.recycle();
- }
-
- public int getCount() {
- return mImageIds.length;
- }
-
- public Object getItem(int position) {
- return position;
- }
-
- public long getItemId(int position) {
- return position;
- }
-
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView i = new ImageView(mContext);
-
- i.setImageResource(mImageIds[position]);
- i.setLayoutParams(new Gallery.LayoutParams(150, 100));
- i.setScaleType(ImageView.ScaleType.FIT_XY);
- i.setBackgroundResource(mGalleryItemBackground);
-
- return i;
- }
-}
-
-First, there are a few member variables, including an array of IDs that reference -the images we placed in our drawable resources directory.
-Next is the constructor, where we define the member Context. The rest of the constructor
-sets up a reference for our Gallery them, which adds the nice framing for each Gallery item.
-Once we have our mGalleryItemBackground, it's important to recycle the
-StyledAttribute for later re-use.
The next three methods are required for basic member queries.
-But then we have the getView() method, which is called
-for each item read by our ImageAdapter, when the Gallery is being built. Here, we
-use our member Context to create a new {@link android.widget.ImageView}. We then define
-the image resource with the current position of the Gallery items (corresponding to our
-array of drawables), set the dimensions for the ImageView,
-set the image scaling to fit the ImageView dimensions, then finally set the
-background theme for the ImageView.
See {@link android.widget.ImageView.ScaleType} -for other image scaling options, in case you want to avoid stretching images that don't -exactly match the ImageView dimensions.
- -You should see something like this:
-
-
-
-A {@link android.widget.GridView} displays items in a two-dimensional, scrolling grid. The items -are acquired from a {@link android.widget.ListAdapter}.
- - --<?xml version="1.0" encoding="utf-8"?> -<GridView xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/gridview" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:numColumns="auto_fit" - android:verticalSpacing="10dp" - android:horizontalSpacing="10dp" - android:columnWidth="90dp" - android:stretchMode="columnWidth" - android:gravity="center" -/> -
onCreate() method:
-
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- GridView gridview = (GridView) findViewById(R.id.gridview);
- gridview.setAdapter(new ImageAdapter(this));
-}
-
- Here, we get a handle on our GridView, from the layout, and give it an Adapter. - We're actually going to create our own Adapter called ImageAdapter.
-
-public class ImageAdapter extends BaseAdapter {
- private Context mContext;
-
- public ImageAdapter(Context c) {
- mContext = c;
- }
-
- public int getCount() {
- return mThumbIds.length;
- }
-
- public Object getItem(int position) {
- return null;
- }
-
- public long getItemId(int position) {
- return 0;
- }
-
- // create a new ImageView for each item referenced by the Adapter
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView;
- if (convertView == null) { // if it's not recycled, initialize some attributes
- imageView = new ImageView(mContext);
- imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
- imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
- imageView.setPadding(8, 8, 8, 8);
- } else {
- imageView = (ImageView) convertView;
- }
-
- imageView.setImageResource(mThumbIds[position]);
- return imageView;
- }
-
- // references to our images
- private Integer[] mThumbIds = {
- R.drawable.sample_2, R.drawable.sample_3,
- R.drawable.sample_4, R.drawable.sample_5,
- R.drawable.sample_6, R.drawable.sample_7,
- R.drawable.sample_0, R.drawable.sample_1,
- R.drawable.sample_2, R.drawable.sample_3,
- R.drawable.sample_4, R.drawable.sample_5,
- R.drawable.sample_6, R.drawable.sample_7,
- R.drawable.sample_0, R.drawable.sample_1,
- R.drawable.sample_2, R.drawable.sample_3,
- R.drawable.sample_4, R.drawable.sample_5,
- R.drawable.sample_6, R.drawable.sample_7
- };
-}
-
- First we take care of some required methods inherited from BaseAdapter.
- The constructor and getCount() are self-explanitory. Normally, getItem()
- should return the actual object at the specified position in our Adapter, but for this Hello World,
- we're not going to bother. Likewise, getItemId() should return the row id of
- the item, but right now we don't care.
However, getView() is the method we care about. This one creates a new View for each image that we
- put in our ImageAdapter. So we're going to create an ImageView each time. When this is called, we're
- going to receive a View, which is likely a recycled View object (at least after the first call), so we
- check for this—if it's null, we initialize the ImageView and setup all the properties we want.
- The LayoutParams() initialization sets the height and width of the View—this ensures
- that no matter the drawable size, each image is resized and cropped to fit in the ImageView (if necessary).
- With setScaleType(), we say that images should be cropped toward the center (if necessary).
- And finally, we set the padding within the ImageView. (Note that, if the images have various aspect-ratios,
- as they do in this demo, then less padding will cause for more cropping of the image, if it does not match
- the dimensions given to the ImageView.) At the end of getView() we set the image resource and
- return the ImageView.
All that's left is our array or drawable resources at the bottom.
-Your grid layout should look something like this:
-
-
-Try experimenting with the behaviors of the GridView and ImageView by adjusting their properties. For example, - instead of setting the ImageView LayoutParams, you can try using - {@link android.widget.ImageView#setAdjustViewBounds(boolean)}.
- -A {@link android.widget.LinearLayout} is a GroupView that will lay child View elements -vertically or horizontally.
- - --<?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"> - - <LinearLayout - android:orientation="horizontal" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:layout_weight="1"> - - <TextView - android:text="red" - android:gravity="center_horizontal" - android:background="#aa0000" - android:layout_width="wrap_content" - android:layout_height="fill_parent" - android:layout_weight="1"/> - - <TextView - android:text="green" - android:gravity="center_horizontal" - android:background="#00aa00" - android:layout_width="wrap_content" - android:layout_height="fill_parent" - android:layout_weight="1"/> - - <TextView - android:text="blue" - android:gravity="center_horizontal" - android:background="#0000aa" - android:layout_width="wrap_content" - android:layout_height="fill_parent" - android:layout_weight="1"/> - - <TextView - android:text="yellow" - android:gravity="center_horizontal" - android:background="#aaaa00" - android:layout_width="wrap_content" - android:layout_height="fill_parent" - android:layout_weight="1"/> - - </LinearLayout> - - <LinearLayout - android:orientation="vertical" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:layout_weight="1"> - - <TextView - android:text="row one" - android:textSize="15pt" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:layout_weight="1"/> - - <TextView - android:text="row two" - android:textSize="15pt" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:layout_weight="1"/> - - <TextView - android:text="row three" - android:textSize="15pt" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:layout_weight="1"/> - - <TextView - android:text="row four" - android:textSize="15pt" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:layout_weight="1"/> - - </LinearLayout> - -</LinearLayout> --
Carefully inspect the XML. You'll notice how this layout works a lot like - an HTML layout. There is one parent LinearLayout that is defined to lay - its child elements vertically. The first child is another LinearLayout that uses a horizontal layout - and the second uses a vertical layout. Each LinearLayout contains several {@link android.widget.TextView} - elements.
-onCreate() method:
-
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-}
-
-R.layout.main refers to the main.xml layout file.
You should see the following:
-
-
-Notice how the various XML attributes define the View's behavior.
-Pay attention to the effect of the layout_weight. Try
- experimenting with different values to see how the screen real estate is
- distributed based on the weight of each element.
A {@link android.widget.ListView} is a View that shows items in a vertically scrolling list. The items are - acquired from a {@link android.widget.ListAdapter}.
- - -public class HelloListView extends ListActivity {
- onCreate() method:
-
-@Override
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, COUNTRIES));
- getListView().setTextFilterEnabled(true);
-}
-
- Notice that we don't need to load a layout (at least, not in this case, because we're using
- the whole screen for our list). Instead, we just call setListAdapter() (which automatically
- adds a ListView to the ListActivity), and provide it with an ArrayAdapter that binds a
- simple_list_item_1 layout item to each entry in the COUNTRIES
- array (added next). The next line of code adds a text filter to the ListView, so that when the user
- begins typing, the list will filter the entire view to display only the items that match the entry.
onCreate() method, add the String array:
-
- static final String[] COUNTRIES = new String[] {
- "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
- "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
- "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
- "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
- "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
- "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
- "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
- "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
- "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
- "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
- "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
- "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
- "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
- "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
- "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
- "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
- "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
- "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
- "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
- "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
- "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
- "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
- "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
- "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
- "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
- "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
- "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
- "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
- "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
- "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
- "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
- "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
- "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
- "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
- "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
- "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
- "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
- "Ukraine", "United Arab Emirates", "United Kingdom",
- "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
- "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
- "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
- };
-
-You can scroll the list, or type to filter it. You should see something like this:
-
-
-A MapView allows you to create your own map-viewing Activity. -First, we'll create a simple Activity that can view and navigate a map. Then we will add some overlay items.
- -<application> element:
-
- <uses-library android:name="com.google.android.maps" />-
-<?xml version="1.0" encoding="utf-8"?> -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/mainlayout" - android:orientation="vertical" - android:layout_width="fill_parent" - android:layout_height="fill_parent" > - - <com.google.android.maps.MapView - android:id="@+id/mapview" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:clickable="true" - android:apiKey="INSERT YOUR KEY HERE" - /> - -<RelativeLayout> --
Setting clickable is important. Otherwise, the map does not allow any user interaction.
The android:apiKey must contain an authentic Android Maps API key.
- The API key is generated using the MD5 fingerprint of your application certificate. For the purposes of
- this exercise, you should use the fingerprint of your debug certificate (which cannot be used to release
- your application for Android devices, but will work while developing). See how to
- generate a fingerprint from your
- debug certificate, then register the
- certificate to retieve an API key.
- Insert the API key as the value of the apiKey attribute. If you do not insert a valid
- Maps API key, the application will still run, but no map tiles will load.
public class HelloMapView extends MapActivity {
-
- isRouteDisplayed() method is required, so add it inside the class:
-
-@Override
-protected boolean isRouteDisplayed() {
- return false;
-}
-
-You can actually run this now, but all it does is allow you to pan around the map.
-Android provides a handy {@link android.widget.ZoomControls} widget for zooming in and out of a View.
-MapView can automatically hook one for us by requesting it with the getZoomControls()
-method. Let's do this.
-<LinearLayout - android:id="@+id/zoomview" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_alignBottom="@id/mapview" - android:layout_centerHorizontal="true" -/>- -
It doesn't really matter what kind of ViewGroup we use, because we just want a - container that we can position within our root RelativeLayout.
- -The last two attributes are available only to an element that's a child of a
- RelativeLayout. layout_alignBottom aligns the bottom of this element to the bottom of
- the element identified with a resource tag (which must be a sibling to this element).
- layout_centerHorizontal centers this on the horizontal plane.
-LinearLayout linearLayout; -MapView mapView; -ZoomControls mZoom;
onCreate(). We'll capture the LinearLayout and
- MapView through their layout resources. Then get the ZoomControls from the MapView::
--linearLayout = (LinearLayout) findViewById(R.id.zoomview); -mapView = (MapView) findViewById(R.id.mapview); -mZoom = (ZoomControls) mapView.getZoomControls();- -
By using the ZoomControls object provided by MapView, we don't have to do any of the work - required to actually perform the zoom operations. The ZoomControls widget that MapView - returns for us is already hooked into the MapView and works as soon as we add it to the - layout. The controls will appear whenever the user touches the map, then dissapear after - a few moments of inactivity.
linearLayout.addView(mZoom);
So, we now have full interaction controls. All well and good, but what we really want our map -for is custom markers and layovers. Let's add some Overlay -objects to our map. To do this, we're going to -implement the ItemizedOverlay -class, which can manage a whole set of Overlay items for us.
- -When using Eclipse, right-click the package name in the Eclipse Package Explorer, and select New > Class. Fill-in - the Name field as HelloItemizedOverlay. For the Superclass, enter - com.google.android.maps.ItemizedOverlay. Click the checkbox for Constructors from - superclass. Click Finish.
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
super(boundCenterBottom(defaultMarker));
-public void addOverlay(OverlayItem overlay) {
- mOverlays.add(overlay);
- populate();
-}
-
- Each time we add a new OverlayItem, we must call populate(), which will read each of out
- OverlayItems and prepare them to be drawn.
populate() method to read each OverlayItem, it will make a request to
- createItem(int). We must define this method to properly read from our ArrayList. Replace the
- existing contents of the createItem method with a get() call to our ArrayList:
-
-
-@Override
-protected OverlayItem createItem(int i) {
- return mOverlays.get(i);
-}
-size() method. Replace the existing contents of the
- method with a size request to our ArrayList:
-
- return mOverlays.size();
That's it for the HelloItemizedOverlay class. We're now ready to use it.
- -Go back to the HelloMapView -class. We'll start by creating one OverlayItem, adding to an instance of our HelloItemizedOverlay, -and then adding this to the MapView.
- -
-First, we need the image that we'll use for our map overlay. Here, we'll use the Android on the -right as our marker. Drag this image (or your own) to the res/drawable/ directory of your project workspace.
- -Now we're ready to work in the HelloMapView:
- --List<Overlay> mapOverlays; -Drawable drawable; -HelloItemizedOverlay itemizedOverlay;
onCreate() method. Instantiate the
- new fields:
-
--mapOverlays = mapView.getOverlays(); -drawable = this.getResources().getDrawable(R.drawable.androidmarker); -itemizedoverlay = new HelloItemizedOverlay(drawable);- -
All overlay elements on a map are held by the MapView, so when we want to add some, we must
- first retrieve the List with getOverlays() methods. We instantiate the Drawable, which will
- be used as our map marker, by using our Context resources to get the Drawable we placed in
- the res/drawable/ directory (androidmarker.png). Our HelloItemizedOverlay takes the Drawable in order to set the
- default marker.
-GeoPoint point = new GeoPoint(19240000,-99120000); -OverlayItem overlayitem = new OverlayItem(point, "", "");- -
GeoPoint coordinates are based in microdegrees (degrees * 1e6). The OverlayItem takes this - GeoPoint and two strings. Here, we won't concern ourselves with the strings, which can display - text when we click our marker, because we haven't yet written the click handler for the OverlayItem.
-itemizedoverlay.addOverlay(overlayitem); -mapOverlays.add(itemizedoverlay);
We've sent our droid to Mexico City. Hola, Mundo!
-You should see the following:
-
-
-Because we created our ItemizedOverlay class with an ArrayList, we can continue adding new
-OverlayItems. Try adding another one. Before the addOverlay() method is called, add these lines:
-GeoPoint point2 = new GeoPoint(35410000, 139460000); -OverlayItem overlayitem2 = new OverlayItem(point2, "", ""); --
Run it again... We've sent a new droid to Tokyo. Sekai, konichiwa!
- diff --git a/docs/html/guide/tutorials/views/hello-relativelayout.jd b/docs/html/guide/tutorials/views/hello-relativelayout.jd deleted file mode 100644 index 1b91537..0000000 --- a/docs/html/guide/tutorials/views/hello-relativelayout.jd +++ /dev/null @@ -1,75 +0,0 @@ -page.title=Hello, RelativeLayout -parent.title=Hello, Views -parent.link=index.html -@jd:body - -A {@link android.widget.RelativeLayout} is a ViewGroup that allows you to layout child elements -in positions relative to the parent or siblings elements.
- --<?xml version="1.0" encoding="utf-8"?> -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> - - <TextView - android:id="@+id/label" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:text="Type here:"/> - - <EditText - android:id="@+id/entry" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:background="@android:drawable/editbox_background" - android:layout_below="@id/label"/> - - <Button - android:id="@+id/ok" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_below="@id/entry" - android:layout_alignParentRight="true" - android:layout_marginLeft="10dip" - android:text="OK" /> - - <Button - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_toLeftOf="@id/ok" - android:layout_alignTop="@id/ok" - android:text="Cancel" /> - -</RelativeLayout> --
Pay attention to each of the additional layout_* attributes (besides the
-usual width and height, which are required for all elements). When using relative layout,
-we use attributes like layout_below and layout_toLeftOf to describe
-how we'd like to position each View. Naturally, these are different relative positions, and the
-value of the attribute is the id of the element we want the position relative to.
onCreate() method:
-
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-}
-
-R.layout.main refers to the main.xml layout file.
You should see the following:
-
-
-A {@link android.widget.Spinner} is a widget that allows the user to select an item from a group. -It is similar to a dropdown list and will allow scrolling when the -list exceeds the available vertical space on the screen.
- - --<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:orientation="vertical" - android:padding="10dip" - android:layout_width="fill_parent" - android:layout_height="wrap_content"> - - <TextView - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:layout_marginTop="10dip" - android:text="Please select a planet:" - /> - - <Spinner - android:id="@+id/spinner" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:drawSelectorOnTop="true" - android:prompt="@string/planet_prompt" - /> - -</LinearLayout> --
Notice that the Spinner's android:prompt is a string resource. In
- this case, Android does not allow it to be a string, it must be a reference to a resource.
- So...
<string>
-element inside the <resources> element:
--<string name="planet_prompt">Choose a planet</string> --
-<resources> - - <string-array name="planets"> - <item>Mercury</item> - <item>Venus</item> - <item>Earth</item> - <item>Mars</item> - <item>Jupiter</item> - <item>Saturn</item> - <item>Uranus</item> - <item>Neptune</item> - </string-array> - -</resources> --
This is the list of items (planets) that the user can select from in the Spinner widget.
-
-@Override
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- Spinner s = (Spinner) findViewById(R.id.spinner);
- ArrayAdapter adapter = ArrayAdapter.createFromResource(
- this, R.array.planets, android.R.layout.simple_spinner_item);
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- s.setAdapter(adapter);
-}
-
- That's it. We start by creating a Spinner from our layout. We then create an {@link android.widget.ArrayAdapter}
- that binds each element of our string array to a layout view—we pass createFromResource our Context,
- the array of selectable items and the type of layout we'd like each one bound to. We then call
- setDropDownViewResource() to define the type of layout in which to present the
- entire collection. Finally, we set this Adapter to associate with our Spinner,
- so the string items have a place to go.
It should look like this:
-
-
-
-A {@link android.widget.TableLayout} is a ViewGroup that -will lay child View elements into rows and columns.
- - --<?xml version="1.0" encoding="utf-8"?> -<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:stretchColumns="1"> - - <TableRow> - <TextView - android:layout_column="1" - android:text="Open..." - android:padding="3dip" /> - <TextView - android:text="Ctrl-O" - android:gravity="right" - android:padding="3dip" /> - </TableRow> - - <TableRow> - <TextView - android:layout_column="1" - android:text="Save..." - android:padding="3dip" /> - <TextView - android:text="Ctrl-S" - android:gravity="right" - android:padding="3dip" /> - </TableRow> - - <TableRow> - <TextView - android:layout_column="1" - android:text="Save As..." - android:padding="3dip" /> - <TextView - android:text="Ctrl-Shift-S" - android:gravity="right" - android:padding="3dip" /> - </TableRow> - - <View - android:layout_height="2dip" - android:background="#FF909090" /> - - <TableRow> - <TextView - android:text="X" - android:padding="3dip" /> - <TextView - android:text="Import..." - android:padding="3dip" /> - </TableRow> - - <TableRow> - <TextView - android:text="X" - android:padding="3dip" /> - <TextView - android:text="Export..." - android:padding="3dip" /> - <TextView - android:text="Ctrl-E" - android:gravity="right" - android:padding="3dip" /> - </TableRow> - - <View - android:layout_height="2dip" - android:background="#FF909090" /> - - <TableRow> - <TextView - android:layout_column="1" - android:text="Quit" - android:padding="3dip" /> - </TableRow> -</TableLayout> --
Notice how this resembles the structure of an HTML table. TableLayout is like the
-table element; TableRow is like a tr element; but for our cells like
-the html td element, we can use any kind of View. Here, we use TextView for the cells.
onCreate() method:
-
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-}
-
-R.layout.main refers to the main.xml layout file.
You should see the following:
-
-
-A {@link android.widget.TabWidget} offers the ability to easily draw an interface that uses -tabs to navigate between different views.
- --<?xml version="1.0" encoding="utf-8"?> -<TabHost xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@android:id/tabhost" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> - <LinearLayout - android:orientation="vertical" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> - <TabWidget - android:id="@android:id/tabs" - android:layout_width="fill_parent" - android:layout_height="wrap_content" /> - <FrameLayout - android:id="@android:id/tabcontent" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> - <TextView - android:id="@+id/textview1" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:text="this is a tab" /> - <TextView - android:id="@+id/textview2" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:text="this is another tab" /> - <TextView - android:id="@+id/textview3" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:text="this is a third tab" /> - </FrameLayout> - </LinearLayout> -</TabHost> --
Here, we've created a {@link android.widget.TabHost} that contains the entire layout of the Activity. - A TabHost requires two descendant elements: a {@link android.widget.TabWidget} and a {@link android.widget.FrameLayout}. - In order to properly layout these elements, we've put them inside a vertical {@link android.widget.LinearLayout}. - The FrameLayout is where we keep the content that will change with each tab. Each child in the FrameLayout will - be associated with a different tab. - In this case, each tab simply shows a different {@link android.widget.TextView} with some text.
-Notice that the TabWidget and the FrameLayout elements have specific android namespace IDs. These are necessary
- so that the TabHost can automatically retireve references to them, populate the TabWidget with the tabs that we'll define
- in our code, and swap the views in the FrameLayout. We've also defined our own IDs for each TextView, which we'll use to
- associate each tab with the view that it should reveal.
Of course, you can - make these child views as large as complex as you'd like — instead of the TextView elements, - you could start with other layout views and build a unique layout hierarchy for each tab.
- -TabActivity.
- By default, Eclipse creates a class that extends Activity. Change it to
- extend TabActivity:
-public class HelloTabWidget extends TabActivity {
-
- onCreate method like this:
-
-public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- mTabHost = getTabHost();
-
- mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(R.id.textview1));
- mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(R.id.textview2));
- mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(R.id.textview3));
-
- mTabHost.setCurrentTab(0);
-}
-
- As usual, we start by setting our layout.
-We then call the TabActivity method getTabHost(),
- which returns us a reference to the TabHost we created in our layout. Upon our TabHost, we call addTab()
- for each of the tabs that we want to add to the TabWidget. Each time we call this, we pass a
- {@link android.widget.TabHost.TabSpec} that we build on the fly, and with it, chain together two necessary methods:
- setIndicator() to set the text for the tab button, and setContent() to define
- which View we want to associate with the tab and reveal when pressed. Our indicator is just a text string and
- our content is an ID reference to the TextView elements we inserted in the FrameLayout.
At the end, we call setCurrentTab() to define which tab should be opened by default. The tabs
- are saved like a zero-based array, so to open the first tab, we pass zero (0).
<application> tag. It should end up like this:
- -<application android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar"> --
Your application should look like this:
-
-
-You can include icons in your tabs by passing a
-{@link android.graphics.drawable.Drawable} when you call setIndicator(). Here's an example
-that uses a Drawable created from an image in the project resources:
setIndicator("TAB 1", getResources().getDrawable(R.drawable.tab_icon))
-A {@link android.widget.TimePicker} is a widget that allows the -user to select the time by hour, minute and AM or PM.
- - --<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:orientation="vertical"> - - <TextView android:id="@+id/timeDisplay" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text=""/> - - <Button android:id="@+id/pickTime" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Change the time"/> - -</LinearLayout> --
For the layout, we're using a vertical LinearLayout, with a {@link android.widget.TextView} that - will display the time and a {@link android.widget.Button} that will initiate the - {@link android.widget.TimePicker} dialog. - With this layout, the TextView will sit above the Button. - The text value in the TextView is set empty, as it will be filled by our Activity - with the current time.
-
-private TextView mTimeDisplay;
-private Button mPickTime;
-
-private int mHour;
-private int mMinute;
-
-static final int TIME_DIALOG_ID = 0;
-
-@Override
-protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- // capture our View elements
- mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
- mPickTime = (Button) findViewById(R.id.pickTime);
-
- // add a click listener to the button
- mPickTime.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- showDialog(TIME_DIALOG_ID);
- }
- });
-
- // get the current time
- final Calendar c = Calendar.getInstance();
- mHour = c.get(Calendar.HOUR_OF_DAY);
- mMinute = c.get(Calendar.MINUTE);
-
- // display the current date
- updateDisplay();
-}
-
-Tip: Press Ctrl(or Cmd) + Shift + O to import all needed packages.
-We start by instantiating variables for our View elements and time fields.
- The TIME_DIALOG_ID is a static integer that uniquely identifies the dialog. In the
- onCreate() method, we get prepared by setting the layout and capturing the View elements.
- We then set an on-click listener for the Button, so that when it is clicked, it will
- show our TimePicker dialog. The showDialog() method will perform a callback
- to our Activity. (We'll define this callback in the next section.) We then create an
- instance of {@link java.util.Calendar} and get the current hour and minute. Finally, we call
- updateDisplay()—our own method that will fill the TextView with the time.
onCreate() method, add the onCreateDialog() callback method:
-
-@Override
-protected Dialog onCreateDialog(int id) {
- switch (id) {
- case TIME_DIALOG_ID:
- return new TimePickerDialog(this,
- mTimeSetListener, mHour, mMinute, false);
- }
- return null;
-}
-
- This is passed the identifier we gave showDialog() and initializes
- the TimePicker to the time we retrieved from our Calendar instance. It will be called by
- showDialog().
updateDisplay() method:
-
-// updates the time we display in the TextView
-private void updateDisplay() {
- mTimeDisplay.setText(
- new StringBuilder()
- .append(pad(mHour)).append(":")
- .append(pad(mMinute)));
-}
-
- This simply takes our member fields for the time and inserts them in
- the mTimeDisplay TextView. Note that we call a new method, pad(),
- on the hour and minute. (We'll create this method in the last step.)
-// the callback received when the user "sets" the time in the dialog
-private TimePickerDialog.OnTimeSetListener mTimeSetListener =
- new TimePickerDialog.OnTimeSetListener() {
- public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
- mHour = hourOfDay;
- mMinute = minute;
- updateDisplay();
- }
- };
-
- Now when the user is done setting the time (clicks the "Set" button), we update our member fields with - the new time and update our TextView.
-pad() method that we called from the updateDisplay():
-
-private static String pad(int c) {
- if (c >= 10)
- return String.valueOf(c);
- else
- return "0" + String.valueOf(c);
-}
-
- This method returns the appropriate String representation of the hour or minute. - It will prefix a zero to the number if it's a single digit. -
-When you press the "Change the time" button, you should see the following:
-
-
-A {@link android.webkit.WebView} allows you to create your own web browser Activity. In this tutorial, -we'll create a simple Activity that can view web pages.
- --<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:orientation="vertical"> - - <WebView - android:id="@+id/webview" - android:layout_width="fill_parent" - android:layout_height="fill_parent" - /> - -</LinearLayout> -
WebView webview;-
Then add the following at the end of the onCreate() method:
-webview = (WebView) findViewById(R.id.webview);
-webview.getSettings().setJavaScriptEnabled(true);
-webview.loadUrl("http://www.google.com");
-
-
- This captures the WebView we created in our layout, then requests a - {@link android.webkit.WebSettings} object and enables JavaScript. - Then we load a URL.
<manifest> element:
-
- <uses-permission android:name="android.permission.INTERNET" />
You now have the world's simplest web page viewer. - It's not quite a browser yet. It only loads the page we've requested.
- -We can load a page, but as soon as we click a link, the default Android web browser -handles the Intent, instead of our own WebView handling the action. So now we'll -override the {@link android.webkit.WebViewClient} to enable us to handle our own URL loading.
- -
-private class HelloWebViewClient extends WebViewClient {
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- view.loadUrl(url);
- return true;
- }
-}onCreate() method, set an instance of the HelloWebViewClient
- as our WebViewClient:
- webview.setWebViewClient(new WebViewClientDemo());- -
This line should immediately follow the initialization of our WebView object.
-What we've done is create a WebViewClient that will load any URL selected in our
-WebView in the same WebView. You can see this in the shouldOverrideUrlLoading()
-method, above—it is passed the current WebView and the URL, so all we do
-is load the URL in the given view. Returning true says that we've handled the URL
-ourselves and the event should not bubble-up.
If you try it again, new pages will now load in the HelloWebView Activity. However, you'll notice that -we can't navigate back. We need to handle the back button -on the device, so that it will return to the previous page, rather than exit the application.
-
-@Override
-public boolean onKeyDown(int keyCode, KeyEvent event) {
- if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
- webview.goBack();
- return true;
- }
- return super.onKeyDown(keyCode, event);
-}
- The condition uses a {@link android.view.KeyEvent} to check
- whether the key pressed is the BACK button and whether the
- WebView is actually capable of navigating back (if it has a history). If both are
- not true, then we send the event up the chain (and the Activity will close).
- But if both are true, then we call goBack(),
- which will navigate back one step in the history. We then return true to indicate
- that we've handled the event.
When you open the application, it should look like this:
-
-
-This collection of "Hello World"-style tutorials is designed -to get you quickly started with common Android Views and widgets. The aim is to let you copy and paste -these kinds of boring bits so you can focus on developing the code that makes your Android application rock. -Of course, we'll discuss some of the given code so that it all makes sense.
- -Note that a certain amount of knowledge is assumed for these tutorials. If you haven't -completed the Hello, World tutorial, -please do so—it will teach you many things you should know about basic -Android development and Eclipse features. More specifically, you should know:
-Please, also notice that, in order to make these tutorials simple, some may -not convey the better Android coding practices. In particular, many of them -use hard-coded strings in the layout files—the better practice is to reference strings from -your strings.xml file.
-With this knowledge, you're ready to begin, so take your pick.
- -
-There are plenty more Views and widgets available. See the {@link android.view.View} class
-for more on View layouts, and the {@link android.widget widget package}
-for more useful widgets. And for more raw code samples, visit the
-Api Demos.
-These can also be found offline, in /<sdk>/samples/ApiDemos.