Android Activity Lifecycle and Intents
Android Activity Lifecycle and Intents
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.
Method Description
OnResume called when activity will start interacting with the user.
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 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.
Launch an activity
Broadcast a message
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.
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to
be invoked.
To get the full code of explicit intent, visit the next 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. }
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.
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. }
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).
Method Signature
There are two variants of 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. }
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.
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. }
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.
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. 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
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. }
Output:
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. }
Output:
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. 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
Activity class
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. }
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).
Moreover, service can be bounded by a component to perform interactivity and inter process
communication (IPC).
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.
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.
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
File: activity_next.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: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
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. }
File: AndroidManifest.xml
Output: