Tuesday, 28 February 2017

Hello world first application of android

To run the Hello World application, you need to install at least one Android platform in your SDK environment. If you have not already performed this step, you need to do it now.
To install a platform in Eclipse:
  • In the Android SDK and AVD Manager, choose Available Packages in the left panel.
  • In the right panel, expand the Android Repository list to display the components available for installation.
  • Select at least one platform to install, and click Install Selected. If you aren't sure which platform to install, use the latest version.

Create an AVD

In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
To create an AVD:
  • In Eclipse, select Window > Android SDK and AVD Manager.
  • Select Virtual Devices in the left panel.
  • Click New.... The Create New AVD dialog appears.
  • Type the name of the AVD, such as "my_avd".
  • Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.3.3) you want to run on the emulator. For this tutorial, choose the latest platform that you have installed and ignore the rest of the fields.
  • Click Create AVD.

Create a New Android Project

After you've created an AVD you can move to the next step and start a new Android project in Eclipse.
  • In Eclipse, select File > New > Project.... If the ADT Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain "Android Project". (After you create one or more Android projects, an entry for "Android XML File" will also be available.)
  • Select "Android Project" and click Next


Fill in the project details with the following values:
  • Project name: HelloAndroid
  • Build Target: Select a platform version that is equal to or lower than the target you chose for your AVD.
  • Application name: Hello, Android
  • Package name: com.example.helloandroid (or your own private namespace)
  • Create Activity: HelloAndroid
  • Click Finish.


    Here is a description of each field:
Project Name
This is the Eclipse project name — the name of the directory that contains the project files.
Build Target
This is the version of the Android SDK that you're using to build your application. For example, if you choose Android 2.1, your application will be compiled against the Android 2.1 platform library. The target you choose here does not have to match the target you chose for your AVD; however, the target must be equal to or lower than the target you chose for your AVD. Android applications are forward-compatible, which means an application will run on the platform against which it is built as well as all platforms that are released in the future. For example, an application that is built against the 2.1 platform library will run normally on an AVD or device that is running the 2.3.3. The reverse is not true.
Application Name
This is the human-readable title for your application — the name that appears on the Android device.
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 is generated. Your package name must be unique across all packages installed on the Android system; for this reason, it's important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity.

Create Activity
This is the name for the class stub that is generated by the plugin. This is 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. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.
Min SDK Version
This value specifies the minimum API Level on which your application will run. The Min SDK Version should be the same as the Build Target you chose. For example, if the Build Target is Android 2.1, then the Min SDK Version should be 7 or lower (it can never be higher than 7). For more information, see Android API Levels. 

Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files are generated and stored.
Your Android project is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid). It should look like this:
package com.example.helloandroid;
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);
}
}

Construct the UI

Take a look at the revised code below and then make the same changes to your HelloAndroid class. The bold items are lines that have been added.
package com.example.helloandroid;
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: An easy way to add import packages to your project is to press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse shortcut that identifies missing packages based on your code and adds them for you. You may have to expand the import statements in your code for this to work.
An Android user interface is composed of hierarchies of objects called Views. A View is a drawable object used as an element in your UI layout, such as a button, image, or (in this case) a text label. Each of these objects is a subclass of the View class and the subclass that handles text is TextView.
In this change, you create a TextView with the class constructor, which accepts an Android Context instance as its parameter. A Context is 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, and because your HelloAndroid class is a subclass of Activity, it is also a Context. So, you can pass this as your Context reference to the TextView.
Next, you define the text content with setText().
Finally, you pass the TextView to setContentView() in order to display it as the content for the Activity UI. If your Activity doesn't call this method, then no UI is present and the system will display a blank screen.

Run the Application

The Eclipse plugin makes it easy to run your applications:
  • Select Run > Run.
  • Select "Android Application".
The Eclipse plugin automatically creates a new run configuration for your project and then launches the Android Emulator. Depending on your environment, the Android emulator might take several minutes to boot fully, so please be patient. When the emulator is booted, the Eclipse plugin installs your application and launches the default Activity. You should now see something like this:


Friday, 24 February 2017

User interface inUser Interface In an Android

User Interface

In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups, each of which is a descendant of the 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.

View Hierarchy

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 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.

Layout

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 descendant 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 TextView in your UI, and a <LinearLayout> element creates a 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 XML Layouts.
Tip: You can also draw View and ViewGroups objects in Java code, using the 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, 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.

Widgets

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.
For a list of the widgets provided by Android, see the android.widget package.
Input Events
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 user input events, you need to do one of two things:
  • Define an event listener and register it with the View. More often than not, this is how you'll listen for events. The View class contains a collection of nested interfaces named On <something> Listener, each with a callback method called On<something>(). For example, View.OnClickListener (for handling "clicks" on a View), View.OnTouchListener (for handling touch screen events in a View), and 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 setOnClickListener().
  • Override an existing callback method for the View. This is what you should do when you've implemented your own View class and want to listen for specific events that occur within it. Example events you can handle include when the screen is touched (onTouchEvent()), when the trackball is moved (onTrackballEvent()), or when a key on the device is pressed (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 Input Events document.

Menus

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 onCreateOptionsMenu() or 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 onOptionsItemSelected() or 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.

Monday, 20 February 2017

How to create emulator in ADT eclipse

Using the Emulator

Create an Android Emulator Device

The Android tools include an emulator. The emulator behaves like a real Android device in most cases and allows you to test your application without having a real device. You can emulate one or several devices with different configurations. Each configuration is defined via an "Android Virtual Device" (AVD).
To define an AVD open the "AVD Manager" via Windows → AVD Manager and press "New".
Enter The Following Details-



At the end press the button "Create AVD".This will create the device and display it under the "Virtual devices". To test if your setup is correct, select your device and press "Start".
Your device will be started.




Performance

Try to use a smaller resolution for your emulator as for example HVGA. The emulator gets slower the more pixels its needs to render as it is using software rendering.
Also if you have sufficient memory on your computer, add at least 1 GB of memory to your emulator. This is the value "Device ram size" during the creation of the AVD.

Installation of ADT

You have to install Eclipse IDE to develop Android applications.

After that install ADT (android development kit) plugin in Eclipse IDE.

ADT Plugin for Eclipse

Android Development Tools (ADT) is a plugin for the Eclipse IDE that is designed to give you a powerful, integrated environment in which to build Android applications.
ADT extends the capabilities of Eclipse to let you quickly set up new Android projects, create an application UI, add components based on the Android Framework API, debug your applications using the Android SDK tools, and even export signed (or unsigned) .apk files in order to distribute your application.

Installing ADT Plugin

The sections below provide instructions on how to download and install ADT into your Eclipse environment

Configuring the ADT Plugin

After you've successfully downloaded the ADT as described above, the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory:

Android development tools

Android Development Tools

The Android SDK includes several tools and utilities to help you create, test, and debug your projects. A detailed examination of each developer tool is outside the scope of this book, but it’s worth briefl y reviewing what’s available. For more detail than is included here, check out the Android documentation at: http://code.google.com/android/intro/tools.html
As mentioned earlier, the ADT plug-in conveniently incorporates most of these tools into the Eclipse IDE, where you can access them from the DDMS perspective, including:
  • The Android Emulator An implementation of the Android virtual machine designed to run on your development computer. You can use the emulator to test and debug your android applications.
  • Dalvik Debug Monitoring Service (DDMS) Use the DDMS perspective to monitor and control theDalvik virtual machines on which you’re debugging your applications.
  • Android Asset Packaging Tool (AAPT) Constructs the distributable Android package files (.apk).
  • Android Debug Bridge (ADB) The ADB is a client-server application that provides a link to a running emulator. It lets you copy fi les, install compiled application packages (.apk), and run shell commands.
    The following additional tools are also available:
  • SQLite3 A database tool that you can use to access the SQLite database fi les created and used by Android
  • TraceviewGraphical analysis tool for viewing the trace logs from your Android application
  • MkSDCardCreates an SDCard disk image that can be used by the emulator to simulate an external storage card.
  • dxConverts Java .class bytecode into Android .dexbytecode.
  • activityCreatorScript that builds Ant build fi les that you can then use to compile your Android applications without the ADT plug-in
Let’s take a look at some of the more important tools in more detail.

The Android Emulator

The emulator is the perfect tool for testing and debugging your applications, particularly if you don’t have a real device (or don’t want to risk it) for experimentation.



The emulator is an implementation of the Dalvik virtual machine, making it as valid a platform for running Android applications as any Android phone. Because it’s decoupled from any particular hardware, it’s an excellent baseline to use for testing your applications
A number of alternative user interfaces are available to represent different hardware configurations,each with different screen sizes, resolutions, orientations, and hardware features to simulate a variety of mobile device types.
Full network connectivity is provided along with the ability to tweak the Internet connection speed and latency while debugging your applications. You can also simulate placing and receiving voice calls and SMS messages.
The ADT plug-in integrates the emulator into Eclipse so that it’s launched automatically when you run or debug your projects. If you aren’t using the plug-in or want to use the emulator outside of Eclipse, you can telnet into the emulator and control it from its console. For more details on controlling the emulator, check the documentation at http://code.google.com/android/reference/
emulator.html.
At this stage, the emulator doesn’t implement all the mobile hardware features supported by Android,including the camera, vibration, LEDs, actual phone calls, the accelerometer, USB connections,Bluetooth, audio capture, battery charge level, and SD card insertion/ejection.

Dalvik Debug Monitor Service (DDMS)

The emulator lets you see how your application will look, behave, and interact, but to really see what’s happening under the surface, you need the DDMS. The Dalvik Debug Monitoring Service is a powerful debugging tool that lets you interrogate active processes, view the stack and heap, watch and pause active threads, and explore the filesystem of any active emulator.



The DDMS perspective in Eclipse also provides simplified access to screen captures of the emulator and the logs generated by LogCat.
If you’re using the ADT plug-in, the DDMS is fully integrated into Eclipse and is available from the DDMS perspective. If you aren’t using the plug-in or Eclipse, you can run DDMS from the command line, and it will automatically connect to any emulator that’s running.

The Android Debug Bridge (ADB)

The Android debug bridge (ADB) is a client-service application that lets you connect with an Android Emulator or device. It’s made up of three components: a daemon running on the emulator, a service that runs on your development hardware, and client applications (like the DDMS) that communicate with the daemon through the service.



As a communications conduit between your development hardware and the Android device/emulator,the ADB lets you install applications, push and pull fi les, and run shell commands on the target device.Using the device shell, you can change logging settings, and query or modify SQLite databases available on the device.
The ADT tool automates and simplifies a lot of the usual interaction with the ADB, including application installation and update, log fi les, and fi le transfer (through the DDMS perspective).To learn more about what you can do with the ADB, check out the documentation at http://code.google.com/android/reference/
adb.html.

Thursday, 16 February 2017

Tools required for android programming

Tool Required to learn Android Development :-

The Eclipse IDE.
The Android SDK.
The Android Development Tools(ADT) Eclipse plugin

System Requirements

The sections below describe the system and software requirements for developing Android applications using the Android SDK.

Supported Operating Systems

  • Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)
  • Mac OS X 10.5.8 or later (x86 only)
  • Linux (tested on Ubuntu Linux, Lucid Lynx)
  • GNU C Library (glibc) 2.7 or later is required
  • On Ubuntu Linux, version 8.04 or later is required
  • 64-bit distributions must be capable of running 32-bit applications. For information about how to add support for 32-bit applications.

Wednesday, 15 February 2017

Android Application Architecture...

Android Application Architecture

1.AndroidManifest.xml

An Android application is described in the file AndroidManifest.xml. This file must declare all Activities, Services, BroadcastReceivers and ContentProvider of the application. It must also contain the required permissions for the application. AndroidManifest.xml can be thought as the deployment descriptor for an Android application.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=
"http://schemas.android.com/apk/res/
android"

package="Tutorial.android.
temperature"
 android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label=
@string/app_name">
<activity android:name=".Convert"
android:label="@string/app_name"
<intent-filter>
<action android:name="android.intent.action.
MAIN" 
/>
<category android:name="android.intent.
category.
LAUNCHER"
 />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="9" />
</manifest>



Here is the description for all tags :-
<manifest>
This is the root node of each AndroisManifest.xml. It contains the package-attribute, which points to any package in out Activity. Other Activities-path will base relative to its value.
<manifest xmlns:android="http://schemas.android.com/
apk/res/android" package="org.anddev.android.smstretcher">
<uses-permission>
Describes a security permission, which your package must be granted in order for it to operate correctly (i.e. when you want to send SMS or use the Phone-Contacts). The permissions get granted by the user during installation of your application. Quantity:
<uses-permission android:name=" android.permission.RECEIVE_SMS"/>
<permission>
Declares a security permission that can be used to restrict which applications can access components or features in your (or another) package. Quantity:
<instrumentation>
Declares the code of an instrumentation component that is available to test the functionality of this or another package. See Instrumentation for more details. Quantity
<application>
Root element containing declarations of the application-level components contained in the package. This element can also include global and/or default attributes for the application, such as a label, icon, theme, required permission, etc. Quantity: 0 or 1.
<application android:icon="@drawable/icon">
You can place 0+of each of the following children:
<activity>
An Activity is the primary thing for an application to interact with the user. The initial screen the user sees when launching an application is an activity, and most other screens they use will be implemented as separate activities declared with additional activity tags.
<activity android:name=".Welcome"
android:label="@string/app_name">
Note: Every Activity must have an <activity> tag in the manifest whether it is exposed to the world or intended for use only within its own package. If an Activity has no matching tag in the manifest, you won't be able to launch it. Optionally, to support late runtime lookup, you can include 1+ <intent-filter> elements to describe the actions the activity supports.
<intent-filter>
Declares what kind of Intents a component supports. In addition to the various kinds of values that can be specified under this element, attributes can be given here to supply a unique label, icon, and other information for the action being described.
<intent-filter>
<action>
An action-type that the component supports. Example:
<action android:name="android.intent.action.MAIN" />
<category>
A category-type that the component supports. Example:
<category android:name="android.intent.category.
LAUNCHER" />
<data>
An MIME type, URI scheme, URI authority, or URI path that the component supports. You can also associate 1+ pieces of meta-data with your activity:
<meta-data>
Adds a new piece of meta data to the activity, which clients can retrieve through ComponentInfo.metaData.
<receiver>
An IntentReceiver allows an application to be told about changes to data or actions that happen, even if it is not currently running. As with the activity tag, you can optionally include 1+ <intent-filter> elements that the receiver supports or <meta-data> values, just all the same as with <activity>.
<receiver android:name=".SMSReceiver">
<service>
A Service is a component that can run in the background for an arbitrary amount of time. As with the activity tag, you can optionally include one or more <intent-filter> elements that the service supports or <meta-data> values; see the activity's <intent-filter> and <meta-data> descriptions for more information.
<provider>
A ContentProvider is a component that manages persistent data and publishes it for access by other applications. You can also optionally attach one or more <meta-data> values, as described in the activity's <meta-data> description. Of course all <tags> have to be </closed> or closed <directly/>.
The package attribute defines the base package for the following Java elements. It also must be unique as the Android Marketplace only allows application for a specific package once. Therefore a good habit is to use your reverse domain name as a package to avoid collisions with other developers.
android:versionName and android:versionCode specify the version of your application. versionName is what the user sees and can be any string. versionCode must be an integer and the Android Market uses this to determine if you provided a newer version to trigger the update on devices which have your application installed. You typically start with "1" and increase this value by one if you roll-out a new version of your application.
The tag <activity> defines an Activity. An intent filter is registered for this class which defines that this Activity is started once the application starts (action android:name="android.intent.action.MAIN" ). The category definition category android:name="android.intent.category.
LAUNCHER" defines that this application is added to the application directory on the Android device. The @string/app_name value refer to resource files which contain the actual values. This makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications.
The "uses-sdk" part of the "AndroidManifest.xml" defines the minimal SDK version for which your application is valid. This will prevent your application being installed on devices with older SDK versions.

2. R.java, Resources and Assets

The directory gen in an Android project contains generated values. R.java is a generated class which contains references to resources of the res folder in the project. These resources are defined in the res directory and can be values, menus, layouts, icons or pictures or animations. For example a resource can be an image or an XML file which defines strings.
If you create a new resource, the corresponding reference is automatically created in R.java. The references are static int values, the Android system provides methods to access the corresponding resource. For example to access a String with the reference id R.string.yourString use the method getString(R.string.yourString));.
While the directory res contains structured values which are known to the Android platform the directory assets can be used to store any kind of data. In Java you can access this data via the AssetsManager and the method getAssets().

3. Reference to resources in XML files

In your XML files, e.g. your layout files you can refer to other resources via the @ sign. For example if you want to refer to a color you defined as resources you can refer to it via @color/your_id or if you have defined a "hello" string as resource you can access it via @string/hello .

4. Activities and Layouts

The user interface for Activities is defined via layouts. At runtime, layouts are instances of android.view.ViewGroups . The layout defines the UI elements, their properties and their arrangement.
UI elements are based on the class android.view.View . ViewGroup is a subclass of the class View and a layout can contain UI components ( Views ) or other layouts ( ViewGroups ). You should not nestle ViewGroups too deeply as this has a negative impact on performance.
A layout can be defined via Java code or via XML. You typically uses Java code to generate the layout if you don't know the content until runtime; for example if your layout depends on content which you read from the Internet.
XML based layouts are defined via a resource file in the folder /res/layout . This file specifies the ViewGroups , Views , their relationship and their attributes for a specific layout. If a UI element needs to be accessed via Java code you have to give the UI element an unique id via the android:id attribute. To assign a new id to an UI element use @+id/yourvalue . By conversion this will create and assign a new id yourvalue to the corresponding UI element. In your Java code you can later access these UI elements via the method findViewById(R.id.yourvalue) .
Defining layouts via XML is usually the preferred way as this separates the programming logic from the layout definition. It also allows the definition of different layouts for different devices. You can also mix both approaches.

5. Activities and Lifecycle

The operating system controls the life cycle of your application. At any time the Android system may stop or destroy your application, e.g. because of an incoming call. The Android system defines a life cycle for activities via pre-defined methods. The most important methods are:
  • onSaveInstanceState() - called if the activity is stopped. Used to save data so that the activity can restore its states if re-started
  • onPause() - always called if the Activity ends, can be used to release resource or save data
  • onResume() - called if the Activity is re-started, can be used to initialize fields
The activity will also be restarted if a so called "configuration change" happens. A configuration change for example happens if the user changes the orientation of the device (vertical or horizontal). The activity is in this case restarted to enable the Android platform to load different resources for these configuration, e.g. layouts for vertical or horizontal mode. In the emulator you can simulate the change of the orientation via CNTR+F11.
You can avoid a restart of your application for certain configuration changes via the configChanges attribute on your activity definition in your AndroidManifest.xml. The following activity will not be restarted in case of orientation changes or position of the physical keyboard (hidden / visible).
<activity android:name=".ProgressTestActivity"
android:label="@string/app_name"
android:configChanges="orientation|
keyboardHidden|keyboard"

</activity>

6. Context

The class android.content.Context provides the connections to the Android system. It is the interface to global information about the application environment. Context also provides access to Android Services, e.g. theLocation Service. As Activities and Services extend the class Context you can directly access the context via this.