Anda di halaman 1dari 47

ZxDFc qc`Android Activity Lifecycle

Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The


android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single screen.

The 7 lifecycle method of Activity describes how activity will behave at different states.

Android Activity Lifecycle methods


Let's see the 7 lifecycle methods of android activity.

Method Description

OnCreate called when activity is first created.

OnStart called when activity is becoming visible to the user.

OnResume called when activity will start interacting with the user.

OnPause called when activity is not visible to the user.

OnStop called when activity is no longer visible to the user.

OnRestart called after your activity is stopped, prior to start.


OnDestroy called before the activity is destroyed.

Android Activity Lifecycle Example


It provides the details about the invocation of life cycle methods of activity. In this example,
we are displaying the content on the logcat.
File: MainActivity.java
1. package com.example.activitylifecycle;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.util.Log;
5. import android.view.Menu;
6. public class MainActivity extends Activity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. Log.d("lifecycle","onCreate invoked");
12. }
13. @Override
14. protected void onStart() {
15. super.onStart();
16. Log.d("lifecycle","onStart invoked");
17. }
18. @Override
19. protected void onResume() {
20. super.onResume();
21. Log.d("lifecycle","onResume invoked");
22. }
23. @Override
24. protected void onPause() {
25. super.onPause();
26. Log.d("lifecycle","onPause invoked");
27. }
28. @Override
29. protected void onStop() {
30. super.onStop();
31. Log.d("lifecycle","onStop invoked");
32. }
33. @Override
34. protected void onRestart() {
35. super.onRestart();
36. Log.d("lifecycle","onRestart invoked");
37. }
38. @Override
39. protected void onDestroy() {
40. super.onDestroy();
41. Log.d("lifecycle","onDestroy invoked");
42. }
43. }

download this example

Output:
You will not see any output on the emulator or device. You need to open logcat.

Now see on the logcat: onCreate, onStart and onResume methods are invoked.

Now click on the HOME Button. You will see onPause method is invoked.
After a while, you will see onStop method is invoked.

Now see on the emulator. It is on the home. Now click on the center button to launch the
app again.
Now click on the lifecycleactivity icon.

Now see on the logcat: onRestart, onStart and onResume methods are invoked.
If you see the emulator, application is started again.

Now click on the back button. Now you will see onPause methods is invoked.
After a while, you will see onStop and onDestroy methods are invoked.
The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.

Android Intent Tutorial

Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.

It is generally used with startActivity() method to invoke activity, broadcast receivers etc.

The dictionary meaning of intent is intention or purpose. So, it can be described as the
intention to do action.

The LabeledIntent is the subclass of android.content.Intent class.

Android intents are mainly used to:

Start the service

Launch an activity

Display a web page

Display a list of contacts

Broadcast a message

Dial a phone call etc.


Types of Android Intents
There are two types of intents in android: implicit and explicit.

1) Implicit Intent

Implicit Intent doesn't specifiy the component. In such case, intent provides information
of available components provided by the system that is to be invoked.

For example, you may write the following code to view the webpage.

1. Intent intent=new Intent(Intent.ACTION_VIEW);


2. intent.setData(Uri.parse("http://www.javatpoint.com"));
3. startActivity(intent);

2) Explicit Intent

Explicit Intent specifies the component. In such case, intent provides the external class to
be invoked.

1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);


2. startActivity(i);

To get the full code of explicit intent, visit the next page.

Android Implicit Intent Example


Let's see the simple example of implicit intent that displays a web page.

activity_main.xml

File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6. <EditText
7. android:id="@+id/editText1"
8. android:layout_width="wrap_content"
9. android:layout_height="wrap_content"
10. android:layout_alignParentTop="true"
11. android:layout_centerHorizontal="true"
12. android:layout_marginTop="44dp"
13. android:ems="10" />
14. <Button
15. android:id="@+id/button1"
16. android:layout_width="wrap_content"
17. android:layout_height="wrap_content"
18. android:layout_below="@+id/editText1"
19. android:layout_centerHorizontal="true"
20. android:layout_marginTop="54dp"
21. android:text="Visit" />
22. </RelativeLayout>

Activity class

File: MainActivity.java
1. package org.sssit.implicitintent;
2. import android.net.Uri;
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.Intent;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.EditText;
10. public class MainActivity extends Activity {
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15. final EditText editText1=(EditText)findViewById(R.id.editText1);
16. Button button1=(Button)findViewById(R.id.button1);
17. button1.setOnClickListener(new OnClickListener() {
18. @Override
19. public void onClick(View arg0) {
20. String url=editText1.getText().toString();
21. Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
22. startActivity(intent);
23. }
24. });
25. }
26. }

download this android example


Output:

Android Explicit Intent Example


Android Explicit intent specifies the component to be invoked from activity. In other
words, we can call another activity in android by explicit intent.

We can also pass the information from one activity to another using explicit intent.

Here, we are going to see an example to call one activity from another and vice-versa.

Android calling one activity from another activity


example
Let's see the simple example of android explicit example that calls one activity from another
and vice versa.

activity_main.xml

File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/Button01"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_below="@+id/TextView01"
13. android:layout_marginLeft="65dp"
14. android:layout_marginTop="38dp"
15. android:onClick="onClick"
16. android:text="Call second activity" />
17.
18. <TextView
19. android:id="@+id/TextView01"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_alignLeft="@+id/Button01"
23. android:layout_alignParentTop="true"
24. android:layout_marginLeft="18dp"
25. android:layout_marginTop="27dp"
26. android:minHeight="60dip"
27. android:text="First Activity"
28. android:textSize="20sp" />
29.
30. </RelativeLayout>

activitytwo_main.xml

File: activitytwo_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/Button01"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_below="@+id/TextView01"
13. android:layout_marginLeft="65dp"
14. android:layout_marginTop="38dp"
15. android:onClick="onClick"
16. android:text="Call First activity" />
17.
18. <TextView
19. android:id="@+id/TextView01"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_alignLeft="@+id/Button01"
23. android:layout_alignParentTop="true"
24. android:layout_marginLeft="18dp"
25. android:layout_marginTop="27dp"
26. android:minHeight="60dip"
27. android:text="Second Activity"
28. android:textSize="20sp" />
29.
30. </RelativeLayout>

ActivityOne class

File: MainActivityOne.java
1. package com.example.explicitintent2;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.view.Menu;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.Toast;
10. public class ActivityOne extends Activity {
11. /** Called when the activity is first created. */
12. @Override
13. public void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16. Button button1=(Button)findViewById(R.id.Button01);
17.
18. button1.setOnClickListener(new OnClickListener(){
19. public void onClick(View view) {
20. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
21. i.putExtra("Value1", "Android By Javatpoint");
22. i.putExtra("Value2", "Simple Tutorial");
23. // Set the request code to any code you like, you can identify the
24. // callback via this code
25. startActivity(i);
26. }
27. });
28. }
29. }

ActivityTwo class

File: MainActivityTwo.java
1. package com.example.explicitintent2;
2. import android.app.Activity;
3. import android.content.Intent;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.view.View.OnClickListener;
7. import android.widget.Button;
8. import android.widget.EditText;
9. import android.widget.TextView;
10. import android.widget.Toast;
11. public class ActivityTwo extends Activity {
12. /** Called when the activity is first created. */
13. @Override
14. public void onCreate(Bundle bundle) {
15. super.onCreate(bundle);
16. TextView tv=new TextView(this);
17. tv.setText("second activity");
18. setContentView(R.layout.activity_two);
19. Bundle extras = getIntent().getExtras();
20. String value1 = extras.getString("Value1");
21. String value2 = extras.getString("Value2");
22. Toast.makeText(getApplicationContext(),"Values are:\n First value: "+value1+
23. "\n Second Value: "+value2,Toast.LENGTH_LONG).show();
24. Button button1=(Button)findViewById(R.id.Button01);
25. button1.setOnClickListener(new OnClickListener(){
26. public void onClick(View view) {
27. Intent i = new Intent(getApplicationContext(), ActivityOne.class);
28. startActivity(i);
29. }
30. });
31. }
32. }

download this android example

Output:
Android StartActivityForResult Example
By the help of android startActivityForResult() method, we can get result from another
activity.
By the help of android startActivityForResult() method, we can send information from one
activity to another and vice-versa. The android startActivityForResult method, requires a
result from the second activity (activity to be invoked).

In such case, we need to override the onActivityResult method that is invoked


automatically when second activity returns result.

Method Signature
There are two variants of startActivityForResult() method.

1. public void startActivityForResult (Intent intent, int requestCode)


2. public void startActivityForResult (Intent intent, int requestCode, Bundle options)

Android StartActivityForResult Example


Let's see the simple example of android startActivityForResult method.

activity_main.xml

Drag one textview and one button from the pallete, now the xml file will look like this.

File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10. <TextView
11. android:id="@+id/textView1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignLeft="@+id/button1"
15. android:layout_alignParentTop="true"
16. android:layout_marginTop="48dp"
17. android:text="Default Message" />
18. <Button
19. android:id="@+id/button1"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_below="@+id/textView1"
23. android:layout_centerHorizontal="true"
24. android:layout_marginTop="42dp"
25. android:text="GetMessage" />
26. </RelativeLayout>

second_main.xml

This xml file is created automatically when you create another activity. To create new
activity Right click on the package inside the src -> New -> Other ->Android
Activity.

Now drag one editText, one textView and one button from the pallete, now the xml file will
look like this:

File: second_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".SecondActivity" >
10. <EditText
11. android:id="@+id/editText1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_marginTop="61dp"
16. android:layout_toRightOf="@+id/textView1"
17. android:ems="10" />
18. <TextView
19. android:id="@+id/textView1"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_alignBaseline="@+id/editText1"
23. android:layout_alignBottom="@+id/editText1"
24. android:layout_alignParentLeft="true"
25. android:text="Enter Message:" />
26. <Button
27. android:id="@+id/button1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_below="@+id/editText1"
31. android:layout_centerHorizontal="true"
32. android:layout_marginTop="34dp"
33. android:text="Submit" />
34. </RelativeLayout>

Activity class

Now let's write the code that invokes another activity and get result from that activity.

File: MainActivity.java
1. package com.javatpoint.startactivityforresult;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.view.Menu;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.TextView;
10. public class MainActivity extends Activity {
11. TextView textView1;
12. Button button1;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. textView1=(TextView)findViewById(R.id.textView1);
18. button1=(Button)findViewById(R.id.button1);
19. button1.setOnClickListener(new OnClickListener() {
20. @Override
21. public void onClick(View arg0) {
22. Intent intent=new Intent(MainActivity.this,SecondActivity.class);
23. startActivityForResult(intent, 2);// Activity is started with requestCode 2
24. }
25. });
26. }
27. // Call Back method to get the Message form other Activity
28. @Override
29. protected void onActivityResult(int requestCode, int resultCode, Intent data)
30. {
31. super.onActivityResult(requestCode, resultCode, data);
32. // check if the request code is same as what is passed here it is 2
33. if(requestCode==2)
34. {
35. String message=data.getStringExtra("MESSAGE");
36. textView1.setText(message);
37. }
38. }
39. @Override
40. public boolean onCreateOptionsMenu(Menu menu) {
41. // Inflate the menu; this adds items to the action bar if it is present.
42. getMenuInflater().inflate(R.menu.main, menu);
43. return true;
44. }
45. }

SecondActivity class

Let's write the code that displays the content of second activity layout file.

File: SecondActivity.java
1. package com.javatpoint.startactivityforresult;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.view.Menu;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.EditText;
10. import android.widget.TextView;
11. public class SecondActivity extends Activity {
12. EditText editText1;
13. Button button1;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_second);
18. editText1=(EditText)findViewById(R.id.editText1);
19. button1=(Button)findViewById(R.id.button1);
20. button1.setOnClickListener(new OnClickListener() {
21. @Override
22. public void onClick(View arg0) {
23. String message=editText1.getText().toString();
24. Intent intent=new Intent();
25. intent.putExtra("MESSAGE",message);
26. setResult(2,intent);
27. finish();//finishing activity
28. }
29. });
30. }
31. @Override
32. public boolean onCreateOptionsMenu(Menu menu) {
33. // Inflate the menu; this adds items to the action bar if it is present.
34. getMenuInflater().inflate(R.menu.second, menu);
35. return true;
36. }
37. }

download this android example


Output:
Android Fragments
Android Fragment is the part of activity, it is also known as sub-activity. There can be
more than one fragment in an activity. Fragments represent multiple screen inside one
activity.

Android fragment lifecycle is affected by activity lifecycle because fragments are included in
activity.

Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.

The FragmentManager class is responsible to make interaction between fragment objects.

Android Fragment Lifecycle


The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods
for fragment.

No. Method Description

1) onAttach(Activity) it is called only once when it is attached with activit

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, creates and returns view hierarchy.


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() met

5) onViewStateRestored(Bundle) It provides information to the fragment that all the


state of fragment view hierarchy has been restored

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10 onDestroyView() allows the fragment to clean up resources.


)

11 onDestroy() allows the fragment to do final clean up of fragmen


)

12 onDetach() It is called immediately prior to the fragment no lon


) associated with its activity.

Android Fragment Example


Let's have a look at the simple example of android fragment.

activity_main.xml

File: activity_main.xml
1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. android:layout_width="fill_parent"
3. android:layout_height="fill_parent" >
4.
5. <fragment
6. android:id="@+id/fragment2"
7. android:name="com.example.fragmentexample.Fragment2"
8. android:layout_width="0px"
9. android:layout_height="match_parent"
10. android:layout_weight="1"
11. />
12.
13. <fragment
14. android:id="@+id/fragment1"
15. android:name="com.example.fragmentexample.Fragment1"
16. android:layout_width="0px"
17. android:layout_height="match_parent"
18. android:layout_weight="1"
19. />
20.
21. </LinearLayout>

File: fragment1.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:orientation="vertical"
6. android:background="#00ff00"
7. >
8.
9. <TextView
10. android:id="@+id/textView1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:text="fragment frist"
14. android:textAppearance="?android:attr/textAppearanceLarge" />
15.
16. </LinearLayout>

File: fragment2.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:orientation="vertical"
6. android:background="#0000ff"
7. >
8.
9. <TextView
10. android:id="@+id/textView1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:text="Second Fragment"
14. android:textAppearance="?android:attr/textAppearanceLarge" />
15.
16. </LinearLayout>

MainActivity class

File: MainActivity.java
1. package com.example.fragmentexample;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. public class MainActivity extends Activity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }

File: Fragment1.java
1. package com.example.fragmentexample;
2.
3. import android.app.Fragment;
4. import android.os.Bundle;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment1 extends Fragment {
10. @Override
11. public View onCreateView(LayoutInflater inflater, ViewGroup container,
12. Bundle savedInstanceState) {
13. // TODO Auto-generated method stub
14. return inflater.inflate(R.layout.fragment1,container, false);
15. }
16.
17. }

File: Fragment2.java
1. package com.example.fragmentexample;
2.
3. import android.app.Fragment;
4. import android.os.Bundle;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment2 extends Fragment {
10.
11. public View onCreateView(LayoutInflater inflater, ViewGroup container,
12. Bundle savedInstanceState) {
13. // TODO Auto-generated method stub
14. return inflater.inflate(R.layout.fragment2,container, false);
15. }
16.
17. }

download android fragment example

Output:
Android Option Menu Example
Android Option Menus are the primary menus of android. They can be used for settings,
search, delete item etc.

Here, we are going to see two examples of option menus. First, the simple option menus
and second, options menus with images.

Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To
perform event handling on menu items, you need to
override onOptionsItemSelected() method of Activity class.

Android Option Menu Example


Let's see how to create menu in android. Let's see the simple option menu example that
contains three menu items.

activity_main.xml

We have only one textview in this file.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="@string/hello_world" />
15.
16. </RelativeLayout>
menu_main.xml

It contains three items as show below. It is created automatically inside the res/menu
directory.
File: menu_main.xml

1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >


2. <item android:id="@+id/item1"
3. android:title="Item 1"/>
4. <item android:id="@+id/item2"
5. android:title="Item 2"/>
6. <item android:id="@+id/item3"
7. android:title="Item 3"/>
8. </menu>

Activity class

This class displays the content of menu.xml file and performs event handling on clicking the
menu items.

File: MainActivity.java

1. package com.javatpoint.optionmenu;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.view.MenuItem;
6. import android.widget.Toast;
7. public class MainActivity extends Activity {
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. @Override
14. public boolean onCreateOptionsMenu(Menu menu) {
15. // Inflate the menu; this adds items to the action bar if it is present.
16. getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
17. return true;
18. }
19. @Override
20. public boolean onOptionsItemSelected(MenuItem item) {
21. switch (item.getItemId()) {
22. case R.id.item1:
23. Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_L
ONG).show();
24. return true;
25. case R.id.item2:
26. Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_
LONG).show();
27. return true;
28. case R.id.item3:
29. Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_
LONG).show();
30. return true;
31. default:
32. return super.onOptionsItemSelected(item);
33. }
34. }
35. }

download this android example

Output:

Output without clicking on the menu button.

Output after clicking on the menu button.


Output after clicking on the second menu item .

Option Menu with Icon


You need to have icon images inside the res/drawable directory. The android:icon element is
used to display the icon on the option menu. You can write the string information in the
strings.xml file. But we have written it inside the menu_main.xml file.
File: menu_main.xml

1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >


2. <item android:id="@+id/item1"
3. android:icon="@drawable/add"
4. android:title="Item 1"/>
5. <item android:id="@+id/item2"
6. android:icon="@drawable/minus"
7. android:title="Item 2"/>
8. <item android:id="@+id/item3"
9. android:icon="@drawable/delete"
10. android:title="Item 3"/>
11. </menu>

Android Context Menu Example


Android context menu appears when user press long click on the element. It is also known
as floating menu.

It doesn't support item shortcuts and icons.

Android Context Menu Example


Let's see the simple example of context menu in android.

activity_main.xml

Drag one listview from the pallete, now the xml file will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <ListView
12. android:id="@+id/listView1"
13. android:layout_width="match_parent"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="66dp"
18. android:layout_marginTop="53dp" >
19. </ListView>
20.
21. </RelativeLayout>

Activity class

Let's write the code to display the context menu on press of the listview.

File: MainActivity.java

1. package com.javatpoint.contextmenu;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.ContextMenu;
5. import android.view.ContextMenu.ContextMenuInfo;
6. import android.view.Menu;
7. import android.view.MenuItem;
8. import android.view.View;
9. import android.widget.AdapterView;
10. import android.widget.ArrayAdapter;
11. import android.widget.ListView;
12. import android.widget.Toast;
13. public class MainActivity extends Activity {
14. ListView listView1;
15. String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20. listView1=(ListView)findViewById(R.id.listView1);
21. ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.lay
out.simple_list_item_1,contacts);
22. listView1.setAdapter(adapter);
23. // Register the ListView for Context menu
24. registerForContextMenu(listView1);
25. }
26. @Override
27. public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo)
28. {
29. super.onCreateContextMenu(menu, v, menuInfo);
30. menu.setHeaderTitle("Select The Action");
31. menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
32. menu.add(0, v.getId(), 0, "SMS");
33. }
34. @Override
35. public boolean onContextItemSelected(MenuItem item){
36. if(item.getTitle()=="Call"){
37. Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LON
G).show();
38. }
39. else if(item.getTitle()=="SMS"){
40. Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGT
H_LONG).show();
41. }else{
42. return false;
43. }
44. return true;
45. }
46. }

download this android example

Output:

Output after long press on the listview.


Output after clicking on the context menu.

Android Popup Menu Example


Android Popup Menu displays the menu below the anchor text if space is available otherwise
above the anchor text. It disappears if you click outside the popup menu.

The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

Android Popup Menu Example


Let's see how to create popup menu in android.

activity_main.xml

It contains only one button.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <Button
12. android:id="@+id/button1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="62dp"
18. android:layout_marginTop="50dp"
19. android:text="Show Popup" />
20.
21. </RelativeLayout>
popup_menu.xml

It contains three items as show below. It is created inside the res/menu directory.

File: poupup_menu.xml

1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >


2.
3. <item
4. android:id="@+id/one"
5. android:title="One"/>
6.
7. <item
8. android:id="@+id/two"
9. android:title="Two"/>
10.
11. <item
12. android:id="@+id/three"
13. android:title="Three"/>
14.
15. </menu>

Activity class

It displays the popup menu on button click.

File: MainActivity.java

1. package com.javatpoint.popupmenu;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.view.MenuItem;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.PopupMenu;
10. import android.widget.Toast;
11. public class MainActivity extends Activity {
12. Button button1;
13.
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. button1 = (Button) findViewById(R.id.button1);
20. button1.setOnClickListener(new OnClickListener() {
21.
22. @Override
23. public void onClick(View v) {
24. //Creating the instance of PopupMenu
25. PopupMenu popup = new PopupMenu(MainActivity.this, button1);
26. //Inflating the Popup using xml file
27. popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
28.
29. //registering popup with OnMenuItemClickListener
30. popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListen
er() {
31. public boolean onMenuItemClick(MenuItem item) {
32. Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LE
NGTH_SHORT).show();
33. return true;
34. }
35. });
36.
37. popup.show();//showing popup menu
38. }
39. });//closing the setOnClickListener method
40. }
41. }

download this android example

Output:
Android Service Tutorial
Android service is a component that is used to perform operations on the backgroundsuch
as playing music, handle network transactions, interacting content providers etc. It doesn't
has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter process
communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

Note: Android service is not a thread or separate process.

Life Cycle of Android Service


There can be two forms of a service.The lifecycle of service can follow two different paths:
started or bound.

1. Started

2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it
runs in the background indefinitely. It is stopped by stopService() method. The service can
stop itself by calling the stopSelf() method.

2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. The
client can unbind the service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the service.

Understanding Started and Bound Service by background music example

Suppose, I want to play music in the background, so call startService() method. But I want
to get information of the current song being played, I will bind the service that provides
information about the current song.

Android Service Example


Let's see the example of service in android that plays an audio in the background. Audio will
not be stopped even if you switch to another activity. To stop the audio, you need to stop
the service.

activity_main.xml

Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <Button
12. android:id="@+id/buttonStart"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_centerHorizontal="true"
17. android:layout_marginTop="19dp"
18. android:text="Start Service" />
19.
20. <Button
21. android:id="@+id/buttonStop"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_above="@+id/buttonNext"
25. android:layout_alignRight="@+id/buttonStart"
26. android:layout_marginBottom="35dp"
27. android:text="Stop Service" />
28.
29. <Button
30. android:id="@+id/buttonNext"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:layout_alignLeft="@+id/buttonStop"
34. android:layout_centerVertical="true"
35. android:text="Next Page" />
36.
37. </RelativeLayout>
activity_next.xml

It is the layout file of next activity.

File: activity_next.xml

It contains only one textview displaying the message Next Page

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="96dp"
18. android:layout_marginTop="112dp"
19. android:text="Next Page" />
20.
21. </RelativeLayout>

Service class

Now create the service implemenation class by inheriting the Service class and overridding
its callback methods.

File: MyService.java

1. package com.example.serviceexampleaudio;
2.
3. import android.app.Service;
4. import android.content.Intent;
5. import android.media.MediaPlayer;
6. import android.os.IBinder;
7. import android.widget.Toast;
8. public class MyService extends Service {
9. MediaPlayer myPlayer;
10. @Override
11. public IBinder onBind(Intent intent) {
12. return null;
13. }
14. @Override
15. public void onCreate() {
16. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
17.
18. myPlayer = MediaPlayer.create(this, R.raw.sun);
19. myPlayer.setLooping(false); // Set looping
20. }
21. @Override
22. public void onStart(Intent intent, int startid) {
23. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
24. myPlayer.start();
25. }
26. @Override
27. public void onDestroy() {
28. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
29. myPlayer.stop();
30. }
31. }

Activity class

Now create the MainActivity class to perform event handling. Here, we are writing the code
to start and stop service. Additionally, calling the second activity on buttonNext.

File: MainActivity.java

1. package com.example.serviceexampleaudio;
2. import android.app.Activity;
3. import android.content.Intent;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.view.View.OnClickListener;
7. import android.widget.Button;
8. public class MainActivity extends Activity implements OnClickListener {
9. Button buttonStart, buttonStop,buttonNext;
10. @Override
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_main);
14.
15. buttonStart = (Button) findViewById(R.id.buttonStart);
16. buttonStop = (Button) findViewById(R.id.buttonStop);
17. buttonNext = (Button) findViewById(R.id.buttonNext);
18.
19. buttonStart.setOnClickListener(this);
20. buttonStop.setOnClickListener(this);
21. buttonNext.setOnClickListener(this);
22. }
23. public void onClick(View src) {
24. switch (src.getId()) {
25. case R.id.buttonStart:
26. startService(new Intent(this, MyService.class));
27. break;
28. case R.id.buttonStop:
29. stopService(new Intent(this, MyService.class));
30. break;
31. case R.id.buttonNext:
32. Intent intent=new Intent(this,NextPage.class);
33. startActivity(intent);
34. break;
35. }
36. }
37. }

NextPage class

Now, create another activity.

File: NextPage.java

1. package com.example.serviceexampleaudio;
2. import android.app.Activity;
3. import android.os.Bundle;
4.
5. public class NextPage extends Activity {
6. @Override
7. public void onCreate(Bundle savedInstanceState) {
8. super.onCreate(savedInstanceState);
9. setContentView(R.layout.activity_next);
10. }
11. }

Declare the Service in the AndroidManifest.xml file

Finally, declare the service in the manifest file.

File: AndroidManifest.xml

Let's see the complete AndroidManifest.xml file

1. <?xml version="1.0" encoding="utf-8"?>


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.example.serviceexampleaudio"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />
10.
11. <application
12. android:allowBackup="true"
13. android:icon="@drawable/ic_launcher"
14. android:label="@string/app_name"
15. android:theme="@style/AppTheme" >
16. <activity
17. android:name="com.example.serviceexampleaudio.MainActivity"
18. android:label="@string/app_name" >
19. <intent-filter>
20. <action android:name="android.intent.action.MAIN" />
21.
22. <category android:name="android.intent.category.LAUNCHER" />
23. </intent-filter>
24. </activity>
25.
26. <service
27. android:name=".MyService"
28. android:enabled="true" />
29. <activity
30. android:name=".NextPage"/>
31. </application>
32.
33. </manifest>

download this android example

Output: