Now in this tutorial i’ll explain each android application components,how you can build these components and connect to each other using Intents.Basically Android’s Application framework helps you to create different type of android applications using some reusable components. App Components Official Website.

Android Application Components

  • Intent and Intent Filters
  • Activities
  • Services
  • Content Providers
  • App Widgets
  • Processes and Threads

Now let’s start with andorid application components explaination

Intent

An intent is a communicating object through which you can request an action from other android application components,it also provide communication between android application components.There are three basic purposes of intent

  • To start an Activity
  • To start a Service
  • To deliver a Broadcast

There are two types of intent

  • Explicit Intent(start component by name typical action)
// Executed in an Activity, so 'this' is the Context
// The fileUrl is a string URL, such as "http://www.example.com/image.png"
Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);
    • Implicit Intent(start component not by name performing general action)
// Create the text message with a string
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");

// Verify that the intent will resolve to an activity
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(sendIntent);
}

 

What is Intent Filter?

Intent filter is an expression in app’s manifest file which find out the type of intents that any particular component wants to receive.

How to build Intent?

An Intent contain  information that the Android System uses to find out which component to start and also that information which recipient component uses to perform any action

Information contained in an intent is as follows

  • Component Name(name of the component to start by Intent)
  • Action(action to perform such as ACTION_VIEW,ACTION_SEND)
  • Data(data to be acted on by )
  • Category(kind of component handle by Intent)
  • Extras(contains some more information to share with another component or passing)
  • Flags(how to start an activity and what should do after starting that particular activity)

Activities

An Activity-ies is an essential android application components which provides  user interface screen which is used by any user to perform actions e.g dial number,play game etc.

Creating an Activity

To create an activity you must create subclass of an Activity.After creating an activity (.java) code will be something like this.

Public class AndroidCodec extends Activity{
}

Now you need to implement some callback methods like onCreate it’s an essential method to display your xml layout using setContentView() method to define your activity User Interface.

Declaring or Registering an activity and manifest file

Now to declare activity within the manifest file to be accessible go to manifest file and add child element
Within this activity element write down (android:name=””) and within commas write down activity name followed by dot(.) after that it will be like this.


Remember one thing if you will not Declare or Register that activity your application might be crashed. You can also declare intent filters with in this element just like above code.

How to start an Activity?

You can start an activity using this method start Activity() by using intent because intent will hold the information which activity to start.e.g

Intent n = new Intent(this,MainActivity.class);
startActivity(n);

You can also pass data bread to another activity which you want to start.

Intent n = new Intent(this,MainActivity.class);
n.putExtras(key,value);
startActivity(n);

In above code key is the tag through which you will get information within another activity using getExtras method.

Start Activity for Result

When you want to receive result then you will use this method startActivityForResult()
to start an activity.To get result from an activity you have to implement onActivityResult()
Here is the example Code

Intent myintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(myintent,cameraData);
@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			Bundle ex = data.getExtras();
			Image = (Bitmap) ex.get("data");
			capturedImage.setImageBitmap(Image);
			Uri selectedImage = data.getData();

			String[] filePathColumn = {MediaStore.Images.Media.DATA};
			Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			filePath = cursor.getString(columnIndex);
		}
		else if(resultCode == RESULT_CANCELED){
			Toast.makeText(getApplicationContext(), "Please Capture Image", Toast.LENGTH_SHORT).show();
		}
		// Toast.makeText(getApplicationContext(), filePath, Toast.LENGTH_SHORT).show(); 
	}

You can also shutdown an activity using these methods finish(),finishActivity().

Activity LifeCycle of an Android Application

Android application components,android,

above picture is taken from official Android Developer Site LifeCycle Diagram.

Some description of activity lifecycle callback methods

  • onCreate()  this callback method is called when activity is being created.
  • onRestart() this callback method is called when an activity is stopped.
  • onStart() this callback method is called when an activity is about to become visible to the user.
  • onResume() this callback method is called before any activity starts interacting with the user.
  • onPause() this callback method is called when another activity become upfront to the user.(Activity being paused)
  • onStop() this callback method is called when no activity is interacting with the user means no more visible to the user.
  • onDestroy() this callback method is called before an activity is destroyed.
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}

Different subtype of Activities

  • Fragment(represents particular portion of UI in an activity) Link
  • Loaders(structure of loading data asynchronously in an activity or fragment which came into existance in Android 3.0) Link
  • Tasks and Back Stack  Link
  • Overview Screen Link

Services

An andorid application components that from perform long operation at the background e.g network transcation,downloading contents for I/O.

There are two basic forms of Services

  • Started(Service is “started” when application component starts it by using this method startService and run indefinitely whether the component is destroyed which started it).
  • Bound(Service is “bound” when an application component binds that service using this method bindService() with components to interact with each others for communication or any other purposes).

A Service is implemented as follows

public class AndroidCodec extends Service{
}

Content Providers

Content Provider android application components handle requests to the data set and define structure for data security.It connects data in one process to run in another process.To access data from content provider you will use ContentResolver object to communicate with the Content Provider.
Further Detailed SubCategories

  • Content Provider Basics:You will learn about how to access Content Provider,requesting permissions and provider data types.Link
  • Creating a Content Provder:You will how to build your own content provider with designing and implementation of Content Provider classes,MIME types and permission.Link
  • Calender Provider:This API is for user calender events like updating something in the calend,remainder,events etc.Link
  • Contacts Provider:It’s a powerful and flexible Android module that manage data stored about people which you see in your contacts application.Link

App Widgets

App Widget is a small application interface which can be displayed or embedded in other applications like Home Screen which will keep you updated by receiving data from any type of server e.g. if you use Widget of Weather Application it will automatically add widget on your Home Screen when it has been installed and by the time it receive updates from server and display to the user.Now Home Screen you can called it App Widget Host More Detailed.

Processes and Threads

When android application components get started and there is no other running component then Android system launch a process with in a single thread of an excution.

Basically by default all components of an application run in a same process

Process LifeCycle

There are five types of processes.

  • Foreground Process(run in foregroud according to the user requirements or what the user currently doing).
  • Visible Process(run in background which can affect user interface).
  • Service Process(a process which is used to run a service or a process that a run service by calling serviceStart()).
  • Background Process(A process which doesn’t have hold on any activity which can kill by the user or by the system).
  • Empty Process(process which doesn’ have hold on any application components.This process is used to restart the component when needed).

Threads

When an application is launched first time it will create a thread which you call “main” and which will handle events dispatchment to UI widget.

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            Bitmap b = loadImageFromNetwork("http://example.com/image.png");
            mImageView.setImageBitmap(b);
        }
    }).start();
}

But the main disadvantage of using threads is when operation grows this will get complicated and hard to maintain so to prevent from this situation best solution is AsyncTask.

AsyncTask:Asychronously process operations.

Different callback methods are

  • onPreExecute
  • doInBackground
  • onPostExecute
public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }

    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}