Vous êtes sur la page 1sur 14

What is Android Operating System has developed a lot in last 15 years.

Starting from black and white phones to recent smart phones or mini computers, mobile OS has come far away. Especially for smart phones, Mobile OS has greatly evolved from Palm OS in 1996 to Windows pocket PC in 2000 then to Blackberry OS and Android. One of the most widely used mobile OS these days is ANDROID. Android does a software bunch comprise not only operating system but also middleware and key applications. Android Inc was founded in Palo Alto of California, U.S. by Andy Rubin, Rich miner, Nick sears and Chris White in 2003. Later Android Inc. was acquired by Google in 2005. After original release there have been number of updates in the original version of Android. Android SDK

A software development kit that enables developers to create applications for the Android platform. The Android SDK includes sample projects with source code, development tools, an emulator, and required libraries to build Android applications. Applications are written using the Java programming language and run on Dalvik, a custom virtual machine designed for embedded use which runs on top of a Linux kernel.

Activity: An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement: onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually callsetContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).

To be of use with Context.startActivity(), all activity classes must have a corresponding <activity> declaration in their package's AndroidManifest.xml. Topics covered here:
1. 2. 3. 4. 5. 6. 7.

Fragments Activity Lifecycle Configuration Changes Starting Activities and Getting Results Saving Persistent State Permissions Process Lifecycle

Developer Guides The Activity class is an important part of an application's overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform's application model. For a detailed perspective on the structure of an Android application and how activities behave, please read the Application Fundamentals and Tasks and Back Stackdeveloper guides. You can also find a detailed discussion about how to create activities in the Activities developer guide. Fragments Starting with HONEYCOMB, Activity implementations can make use of the Fragment class to better modularize their code, build more sophisticated user interfaces for larger screens, and help scale their application between small and large screens. Activity Lifecycle Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits. An activity has essentially four states:

If an activity in the foreground of the screen (at the top of the stack), it is active or running.

If an activity has lost focus but is still visible (that is, a new non-fullsized or transparent activity has focus on top of your activity), it is paused. 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. If an activity is completely obscured by another activity, it is stopped. 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 the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.

There are three key loops you may be interested in monitoring within your activity: The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call toonDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().

The visible lifetime of an activity happens between a call to onStart() until a corresponding call to 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 BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user. The foreground lifetime of an activity happens between a call to onResume() until a corresponding call toonPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.

The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods. public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState);

protected void onStart();

protected void onRestart();

protected void onResume();

protected void onPause();

protected void onStop();

protected void onDestroy(); }

Drawables A instance of a Drawable resource is a general concept for a graphic which can be drawn. The simplest case is a bitmap file, which would be represented in Android via a BitmapDrawable class. Bitmaps are typically stored in one of the res/drawable folders. The Android project creation wizard creates several of these folders by default, you can provide different sized files for different resolutions of Android devices. If you only provide In additional to graphical files, Android supports XML drawables and 9-patch graphics. XML drawables are used to describe shapes (color, border, gradient), State and Transitions and more. 9-patch graphics are used to define which part of a graphic should be increased if the View which uses this graphic is larger then the graphic. Accessing Drawables Drawables can get accessed in XML via @drawable/filename whereby filename is the filename without extension. For example to acceces the hello.png file, you would use @drawable/hello

In Code you can also access Drawables. Most Views accept an resource ID as input parameter. For example the following code shows how to set a Drawable as background to an ImageView. ImageView imageView = (ImageView) findViewById(R.id.image); imageView.setImageResource(R.drawable.hello); The Resources class allows to access individual resources. An instance of Resources can get access via the getResources() method of the Context class. XML Drawables Shape Drawables Shape Drawables are XML files which allow to define a geometric object with colors, borders and gradients which can get assigned to Views. The advantage of using XML Shape Drawables is that they automatically adjust to the correct size. The following listing shows an example of a Shape Drawable. <?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:width="2dp" android:color="#FFFFFFFF" /> <gradient android:endColor="#DDBBBBBB" android:startColor="#DD777777" android:angle="90" />

<corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp" /> </shape>

Toast Notifications A toast notification is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the user's current activity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events. The screenshot below shows an example toast notification from the Alarm application. Once an alarm is turned on, a toast is displayed to assure you that the alarm was set.

A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service, it appears in front of the Activity currently in focus. Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration); toast.show(); This example demonstrates everything you need for most toast notifications. You should rarely need anything else. You may, however, want to position the toast differently or even use your own layout instead of a simple text message. The following sections describe how you can do these things. You can also chain your methods and avoid holding on to the Toast object, like this: Toast.makeText(context, text, duration).show();

Intent An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch anActivity, broadcastIntent to send it to any interested BroadcastReceiver components, andstartService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a backgroundService. An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. Intent Structure The primary pieces of information in an intent are: action -- The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.

data -- The data to operate on, such as a person record in the contacts database, expressed as a Uri.

Intent Resolution There are two primary forms of intents you will use. Explicit Intents have specified a component (via setComponent(ComponentName) or setClass(Context, Class)), which provides the exact class to be run. Often these will not include any other information, simply being a way for an application to launch various internal activities it has as the user interacts with the application.

Implicit Intents have not specified a component; instead, they must include enough information for the system to determine which of the available components is best to run for that intent.

Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!"); startActivity(intent);

ListView The display of elements in a lists is a very common pattern in mobile applications. The user gets a list of items and can scroll through them. If he selects one item, this typically triggers a detailed screen for the selection. Android provides the ListView class which is capable of displaying a scrollable list of items. These items can be of any type. For example the following listing shows a layout file with includes a ListView. <?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" >

<ListView android:id="@+id/mylist" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView>

</LinearLayout>

ListView listView = (ListView) findViewById(R.id.mylist); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" };

// First paramenter - Context // Second parameter - Layout for the row // Third parameter - ID of the View to which the data is written // Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);

// Assign adapter to ListView


listView.setAdapter(adapter);

What is SQLite? SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. In addition it requires only little memory at runtime (approx. 250 KByte). SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in Java) and REAL(similar to double in Java). All other types must be converted into one of these fields before saving them in the database. SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.

SQLite in Android SQLite is available on every Android device. Using an SQLite database in Android does not require any database setup or administration. You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform. Access to an SQLite database involves accessing the filesystem. This can be slow. Therefore it is recommended to perform database operations asynchronously, for example via the AsyncTask class. . If your application creates a database, this database is saved in the directoryDATA/data/APP_NAME/databases/FILENAME. SQLiteDatabase

SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database. More specifically SQLiteDatabase provides the insert(), update() and delete() methods. In addition it provides the execSQL() method, which allows to execute SQL directly. The object ContentValues allows to define key/values. The "key" represents the table column identifier and the "value" represents the content for the table record in this column. ContentValues can be used for inserts and updates of database entries. Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilderclass . rawQuery() directly accepts an SQL statement as input. query() provides a structured interface for specifying the SQL query. SQLiteQueryBuilder is a convenience class that helps to build SQL queries. rawQuery() Example The following gives an example of a rawQuery() call. Cursor cursor = getReadableDatabase(). rawQuery("select * from todo where _id = ?", new String[] { id }); query() Example The following gives an example of a query() call. return database.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, null, null, null, null, null);

Cursor A query returns a Cursor object . A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory. To get the number of elements of the resulting query use the getCount() method. To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached. Cursor provides typed get*() methods, e.g. getLong(columnIndex),getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing. Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.

Vous aimerez peut-être aussi