Tuesday 12 February 2013

Acitivity Life Cycle Example


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}

What is Activity and Activity Life with simple example


Q 1- What is Activity in android ??

An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.
  • An application usually consists of multiple activities that are loosely bound to each other. 
  • Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time.
  • Each activity can then start another activity in order to perform different actions. 
  • Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack").
  • The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack the last visited activity .

    Activity Life Cycle in android applications


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, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called 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 isFinishing() method.
EDIT:
When the Activity first time loads the events are called as below:
onCreate()
onStart()
onResume()
When you click on Phone button the Activity goes to the background & below events are called:
onPause()
onStop()
Exit the phone dialer & below events will be called:
onRestart()
onStart()
onResume()
When you click the back button OR try to finish() the activity the events are called as below:
onPause()
onStop()
onDestroy()

The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:
These states can be broken into 3 main groups as follows:
Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.
Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.
Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.

For Example of an Activity follow this link 

Activity Example

concept about android


. What is Android?

1.1. Android Operation System

Android is an operating system based on Linux with a Java programming interface.
The Android Software Development Kit (Android SDK) provides all necessary tools to develop Android applications. This includes a compiler, debugger and a device emulator, as well as its own virtual machine to run Android programs.
Android is currently primarily developed by Google.
Android allows background processing, provides a rich user interface library, supports 2-D and 3-D graphics using the OpenGL libraries, access to the file system and provides an embedded SQLite database.
Android applications consist of different components and can re-use components of other applications. This leads to the concept of a task in Android; an application can re-use other Android components to archive a task. For example you can trigger from your application another application which has itself registered with the Android system to handle photos. In this other application you select a photo and return to your application to use the selected photo.

1.2. Google Play (Android Market)

Google offers the Google Play service in which programmers can offer their Android application to Android users. Google phones include the Google Play application which allows to install applications.
Google Play also offers an update service, e.g. if a programmer uploads a new version of his application to Google Play, this service will notify existing users that an update is available and allow to install it.
Google Play used to be called Android Market.

1.3. Security and permissions

During deployment on an Android device, the Android system will create a unique user and group ID for every Android application. Each application file is private to this generated user, e.g. other applications cannot access these files.
In addition each Android application will be started in its own process.
Therefore by means of the underlying Linux operating system, every Android application is isolated from other running applications.
If data should be shared, the application must do this explicitly, e.g. via a Service or a ContentProvider.
Android also contains a permission system. Android predefines permissions for certain tasks but every application can define additional permissions.
An Android application declare its required permissions in its AndroidManifest.xml configuration file. For example an application may declare that it requires access to the Internet.
Permissions have different levels. Some permissions are automatically granted by the Android system, some are automatically rejected.
In most cases the requested permissions will be presented to the user before installation of the application. The user needs to decide if these permissions are given to the application.
If the user denies a permission required by the application, this application cannot be installed. The check of the permission is only performed during installation, permissions cannot be denied or granted after the installation.
Not all users pay attention to the required permissions during installation. But some users do and they write negative reviews on Google Play.

Explicity Intent and its example



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Explicity Intent

In an explicit intent, we actually specify the activity that is required to respond to the intent. In other words, we explicitly designate the target component. This is typically used for application internal messages. The code of this post can be found at end.
In an implicit intent, the main power of the android design, we just declare an intent and leave it to the platform to find an activity that can respond to the intent. Here, we do not declare the target component and hence is typically used for activating components of other applications seamlessly
Let’s look at our example:
This example has 2 activities:
  • InvokingActivity
  • InvokedActivity
The InvokingActivity has a button “Invoke Next Activity” which when clicked explicitly calls the InvokedActivityclass. The relevant part of the code is here:
Button invokingButton = (Button)findViewById(R.id.invokebutton);
invokingButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent explicitIntent = new Intent(InvokingActivity.this,InvokedActivity.class);
startActivity(explicitIntent);
}
});
The layout for InvokingActivity is defined in /res/main.xml:
and for InvokedActivity in /res/invokedactivity.xml.
Here are our java code, InvokingActivity.java:
package com.bogotobogo.explicitintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class InvokingActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button invokingButton = (Button)findViewById(R.id.invokebutton);
invokingButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent explicitIntent = new Intent(InvokingActivity.this,InvokedActivity.class);
startActivity(explicitIntent);
}
});
}
}
and InvokedActivity.java:
package com.bogotobogo.explicitintent;
import android.app.Activity;
import android.os.Bundle;
public class InvokedActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.invokedactivity);
}
}

For Implicity Intent follow this link
Implicit Intent

Imlicity Intent concept and its example


-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Imlicity Intent


In last section  we had explained the concepts of intent understanding intent in android. Now, we will move on to a more interesting concept of Implicit Intents and Intent Filters. The code of this post can be found at end.
As described earlier, an implicit intent does not name a target component that should act upon the intent. Android resolves as to which component is best suited to respond to an Implicit Intent. How does this happen?
Basically, an Intent object has the following information (among other things like Component name, extras and flags) which is of interest for implicit intents:
  • Action
  • Category
  • Data
So, Android compares the three (action, category and data) to something called Intent Filters that are declared by probable target components who are willing to accept Implicit Intent calls. i.e. Intent Filters are the way of any component to advertise its own capabilities to the Android system. This is done declaratively in the AndroidManifest.xml file.
So here are some important points to remember:
  1. Implicit Intents do not specify a target component.
  2. Components willing to receive implicit intents have to declare their ability to handle a specific intent by declaring intent filters.
  3. A component can declare any number of Intent Filters.
  4. There can be more than one component that declares the same Intent Filters and hence can respond to the same implicit intent. In that case, the user is presented both the component options and he can choose which one he wants to continue with.
  5. We can set priorities for the intent filters to ensure the order of responses.
There are 3 tests conducted in order to match an intent with intent filters:
  1. Action Test
  2. Category Test
  3. Data Test
Finally, we’ll look at declaring an implicit intent in one activity which will invoke one of the native activities of the platform by matching the intent filters declared by the same.
The ImplicitIntent Activity creates an implicit intent object contacts. This intent object’s component is not set. However, the action is set to android.content.intent.ACTION_VIEW and the data’s URI is set toPeople.CONTENT_URI.
Such an intent matches with the intent filter declared by the view contacts native activity.
So, when we run this application, it displays the native UI for viewing the existing contacts on the phone!
Here is the relevant piece of code for the same:
Button viewContacts = (Button)findViewById(R.id.ViewContacts);
viewContacts.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent contacts = new Intent();
contacts.setAction(android.content.Intent.ACTION_VIEW);
contacts.setData(People.CONTENT_URI);
startActivity(contacts);
}
});
In this manner many of the native applications can be seamlessly invoked as one of the activities in our applications through implicit intents.
Here are our Java code, ImplicitIntent.java:
package com.bogotobogo.implicitintent;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ImplicitIntent extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewContacts();
}
private void ViewContacts() {
try {
Button viewContacts = (Button)findViewById(R.id.ViewContacts);
viewContacts.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent contacts = new Intent();
contacts.setAction(android.content.Intent.ACTION_VIEW);
contacts.setData(People.CONTENT_URI);
startActivity(contacts);
}
});
}catch (ActivityNotFoundException anfe) {
Log.e(“ViewContacts”,”Viewing of Contacts failed”, anfe);
}
}
}

Some Important Topic Of Android With There Practical Example

1- What is Broadcast Receiver in android with example
2-Important android interview questions and answer
3- What is Fragment and it practical example
4-What is Service with an example
5- What are intents in android
6- What is Android
7-What is Activity , Life Cycle and its Practical example
8-Android Fragments with daynamic Fragment example
9-What is Loaders , component, features of Loader in android
10-what is Linux kernel
11-Types of Kernel
12-COMPILATION AND PROJECT BUILDING IN ANDROID
13-Google Map integration in android application 


What are the intents in android and intent example


What is a Intent ?

Intent is basically a message that is passed between components (such as ActivitiesServicesBroadcast Receivers, and Content Providers). So, it is almost equivalent to parameters passed to API calls. The fundamental differences between API calls and intents’ way of invoking components are:
  • API calls are synchronous while intent-based invocations are asynchronous.
  • API calls are compile time binding while intent-based calls are run-time binding.
Of course, Intents can be made to work exactly like API calls by using what are called explicit intents, which will be explained later. But more often than not, implicit intents are the way to go and that is what is explained here.
One component that wants to invoke another has to only express its’ intent to do a job. And any other component that exists and has claimed that it can do such a job through intent-filters, is invoked by the android platform to accomplish the job. This means, both the components are not aware of each other’s existence and can still work together to give the desired result for the end-user.
This invisible connection between components is achieved through the combination of intents, intent-filters and the android platform.
This leads to huge possibilities like:
  • Mix and match or rather plug and play of components at runtime.
  • Replacing the inbuilt android applications with custom developed applications.
  • Component level reuse within and across applications.
  • Service orientation to the most granular level, if I may say.
Here is additional description about intent, almost formal.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch anActivitybroadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent)or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
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. 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.
All Android components that wish to be notified via intents should declare intent filters so that Android knows which intents should go to that component. So, we need to add intent-filter elements to our AndroidManifest.xml file. It looks something like this:
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=
“http://schemas.android.com/apk/res/android”
package=”com.bogotobogo.myContacts”
android:versionCode=”1″
android:versionName=”1.0″>
<application android:icon=”@drawable/icon”
android:label=”@string/app_name”>
<activity android:name=”.myContacts”
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=”4″ />
<uses-permission android:name=
“android.permission.READ_CONTACTS”/>
</manifest>
Note that intent-filter element is under the activity element. In the file, we are declaring that this activity is (1) the main activity for this application and (2) the activity is in the LAUNCHER category, meaning it gets an icon in the Android menu. Because this activity is the main one for the application, Android knows this is the component it should launch when someone chooses the application from the main menu.
Once we have our intent, we need to pass it to Android and get the child activity to launch. Here, we have two options:
  • Call startActivity() with the Intent. This will cause Android to find the best matching activity and pass the intent to the activity for handling. The activity will not be informed when the child activity is complete.
  • Call startActivityForResult(), passing it the intent and a number which is unique to the calling activity. Android will find the best matching activity and pass the intent over to the activity. The activity will be notified when the child activity is complete via onActivityResult() callback.
For Explicity Intent  follow this link
Explicity Intent

For Implicit Intent Follow this link
Implicit Intent



-