Activity Lifecycle With Example in Android
Activity Lifecycle With Example in Android
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.
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.
activity_main.xml
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/
android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.implicitintent.MainActivity">
8.
9. <EditText
10. android:id="@+id/editText"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="60dp"
16. android:ems="10"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintHorizontal_bias="0.575"
19. app:layout_constraintStart_toStartOf="parent"
20. app:layout_constraintTop_toTopOf="parent" />
21.
22. <Button
23. android:id="@+id/button"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_marginRight="8dp"
27. android:layout_marginLeft="156dp"
28. android:layout_marginTop="172dp"
29. android:text="Visit"
30. app:layout_constraintEnd_toEndOf="parent"
31. app:layout_constraintHorizontal_bias="0.0"
32. app:layout_constraintStart_toStartOf="parent"
33. app:layout_constraintTop_toBottomOf="@+id/editText" />
34. </android.support.constraint.ConstraintLayout>
Activity class
File: MainActivity.java
1. package example.javatpoint.com.implicitintent;
2.
3. import android.content.Intent;
4. import android.net.Uri;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7. import android.view.View;
8. import android.widget.Button;
9. import android.widget.EditText;
10.
11. public class MainActivity extends AppCompatActivity {
12.
13. Button button;
14. EditText editText;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. button = findViewById(R.id.button);
22. editText = findViewById(R.id.editText);
23.
24. button.setOnClickListener(new View.OnClickListener() {
25. @Override
26. public void onClick(View view) {
27. String url=editText.getText().toString();
28. Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
29. startActivity(intent);
30. }
31. });
32. }
33. }
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.
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/
android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.explicitintent.FirstActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:layout_marginEnd="8dp"
13. android:layout_marginStart="8dp"
14. android:layout_marginTop="8dp"
15. android:text="First Activity"
16. app:layout_constraintBottom_toBottomOf="parent"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintHorizontal_bias="0.454"
19. app:layout_constraintLeft_toLeftOf="parent"
20. app:layout_constraintRight_toRightOf="parent"
21. app:layout_constraintStart_toStartOf="parent"
22. app:layout_constraintTop_toTopOf="parent"
23. app:layout_constraintVertical_bias="0.06" />
24.
25. <Button
26. android:id="@+id/button"
27. android:layout_width="wrap_content"
28. android:layout_height="wrap_content"
29. android:layout_marginEnd="8dp"
30. android:layout_marginStart="8dp"
31. android:layout_marginTop="392dp"
32. android:onClick="callSecondActivity"
33. android:text="Call second activity"
34. app:layout_constraintEnd_toEndOf="parent"
35. app:layout_constraintStart_toStartOf="parent"
36. app:layout_constraintTop_toTopOf="parent" />
37.
38. </android.support.constraint.ConstraintLayout>
ActivityOne class
File: MainActivityOne.java
1. package example.javatpoint.com.explicitintent;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7.
8. public class FirstActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_first);
14. }
15. public void callSecondActivity(View view){
16. Intent i = new Intent(getApplicationContext(), SecondActivity.class);
17. i.putExtra("Value1", "Android By Javatpoint");
18. i.putExtra("Value2", "Simple Tutorial");
19. // Set the request code to any code you like, you can identify the
20. // callback via this code
21. startActivity(i);
22. }
23.
24. }
activitytwo_main.xml
File: activitytwo_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/
android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.explicitintent.SecondActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:layout_marginEnd="8dp"
13. android:layout_marginStart="8dp"
14. android:layout_marginTop="8dp"
15. android:text="Second Activity"
16. app:layout_constraintBottom_toBottomOf="parent"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintHorizontal_bias="0.454"
19. app:layout_constraintLeft_toLeftOf="parent"
20. app:layout_constraintRight_toRightOf="parent"
21. app:layout_constraintStart_toStartOf="parent"
22. app:layout_constraintTop_toTopOf="parent"
23. app:layout_constraintVertical_bias="0.06" />
24.
25. <Button
26. android:id="@+id/button"
27. android:layout_width="wrap_content"
28. android:layout_height="wrap_content"
29. android:layout_marginEnd="8dp"
30. android:layout_marginStart="8dp"
31. android:layout_marginTop="392dp"
32. android:onClick="callFirstActivity"
33. android:text="Call first activity"
34. app:layout_constraintEnd_toEndOf="parent"
35. app:layout_constraintStart_toStartOf="parent"
36. app:layout_constraintTop_toTopOf="parent" />
37. </android.support.constraint.ConstraintLayout>
ActivityTwo class
File: MainActivityTwo.java
1. package example.javatpoint.com.explicitintent;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Toast;
8.
9. public class SecondActivity extends AppCompatActivity {
10.
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_second);
15. Bundle extras = getIntent().getExtras();
16. String value1 = extras.getString("Value1");
17. String value2 = extras.getString("Value2");
18. Toast.makeText(getApplicationContext(),"Values are:\n First value: "+value1+
19. "\n Second Value: "+value2, Toast.LENGTH_LONG).show();
20. }
21. public void callFirstActivity(View view){
22. Intent i = new Intent(getApplicationContext(), FirstActivity.class);
23. startActivity(i);
24. }
25.
26. }
Intent Filter
27. In android, Intent Filter is an expression in the app’s manifest file (ActivityMainfest.xml) and it is used to
specify the type of intents that the component would like to receive. In case if we create Intent Filter for an
activity, there is a possibility for other apps to start our activity by sending a certain type of intent otherwise
the activity can be started only by an explicit intent.
28.
29. Generally, the Intent Filters (<intent-filter>) whatever we define in the manifest file can be nested in the
corresponding app components and we can specify the type of intents to accept using these three elements.
30.
31. <action>
32.
33. It defines the name of an intended action to be accepted and it must be a literal string value of an action,
not the class constant.
34.
35. <category>
36.
37. It defines the name of an intent category to be accepted and it must be the literal string value of an action,
not the class constant.
38.
39. <data>
40.
41. It defines the type of data to be accepted and by using one or more attributes we can specify various
aspects of the data URI (scheme, host, port, path) and MIME type.
1. package example.javatpoint.com.activitylifecycle;
2.
3. import android.app.Activity;
4. import android.os.Bundle;
5. import android.util.Log;
6.
7. public class MainActivity extends Activity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13. Log.d("lifecycle","onCreate invoked");
14. }
15. @Override
16. protected void onStart() {
17. super.onStart();
18. Log.d("lifecycle","onStart invoked");
19. }
20. @Override
21. protected void onResume() {
22. super.onResume();
23. Log.d("lifecycle","onResume invoked");
24. }
25. @Override
26. protected void onPause() {
27. super.onPause();
28. Log.d("lifecycle","onPause invoked");
29. }
30. @Override
31. protected void onStop() {
32. super.onStop();
33. Log.d("lifecycle","onStop invoked");
34. }
35. @Override
36. protected void onRestart() {
37. super.onRestart();
38. Log.d("lifecycle","onRestart invoked");
39. }
40. @Override
41. protected void onDestroy() {
42. super.onDestroy();
43. Log.d("lifecycle","onDestroy invoked");
44. }
45. }
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.
Intent Filter
An Intent object carries information that the Android system uses to determine which component to start
(such as the exact component name or component category that should receive the intent), plus information
that the recipient component uses in order to properly perform the action (such as the action to take and the
data to act upon).
Action
ACTION_VIEW
Use this action in an intent with startActivity() when you have some information that an activity can
show to the user, such as a photo to view in a gallery app, or an address to view in a map app.
ACTION_SEND
Also known as the share intent, you should use this in an intent with startActivity() when you have some
data that the user can share through another app, such as an email app or social sharing app.
Data
The URI (a Uri object) that references the data to be acted on and/or the MIME type of that data. The
type of data supplied is generally dictated by the intent's action.
Category
A string containing additional information about the kind of component that should handle the
intent. Any number of category descriptions can be placed in an intent, but most intents do not
require a category. Here are some common categories:
CATEGORY_BROWSABLE
The target activity allows itself to be started by a web browser to display data referenced by a link, such
as an image or an e-mail message.
CATEGORY_LAUNCHER
The activity is the initial activity of a task and is listed in the system's application launcher.
Service
Android service is a component that is used to perform operations on the background such 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).
Services in Android are a special component that facilitates an application to run in the background in order
to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains
active in the background so that the user can operate multiple applications at the same time. A user-interface
is not desirable for android services as it is designed to operate long-running processes without any user
intervention. A service can run continuously in the background even if the application is closed or the user
switches to another application. Further, application components can bind itself to service to carry out inter-
process communication(IPC) . There is a major difference between android services and threads, one must
not be confused between the two. Thread is a feature provided by the Operating system to allow the user to
perform operations in the background. While service is an android component that performs a long-running
operation about which the user might not be aware of as it does not have UI.
1. Foreground Services:
Services that notify the user about its ongoing operations are termed as Foreground Services. Users can
interact with the service by the notifications provided about the ongoing task. Such as in downloading a file,
the user can keep track of the progress in downloading and can also pause and resume the process.
2. Background Services:
Background services do not require any user intervention. These services do not notify the user about ongoing
background tasks and users also cannot access them. The process like schedule syncing of data or storing of
data fall under this service.
3. Bound Services:
This type of android service allows the components of the application like activity to bound themselves with
it. Bound services perform their task as long as any application component is bound to it. More than one
component is allowed to bind themselves with a service at a time. In order to bind an application component
with a service bindService() method is used.
The Life Cycle of Android Services
In android, services have 2 possible paths to complete its life cycle namely Started and Bounded.
1. Started Service (Unbounded Service):
By following this path, a service will initiate when an application component calls the startService() method.
Once initiated, the service can run continuously in the background even if the component is destroyed which
was responsible for the start of the service. Two option are available to stop the execution of service:
By calling stopService() method,
The service can stop itself by using stopSelf() method.
2. Bounded Service:
It can be treated as a server in a client-server interface. By following this path, android application
components can send requests to the service and can fetch results. A service is termed as bounded
when an application component binds itself with a service by calling bindService() method. To stop
the execution of this service, all the components must unbind themselves from the service by
using unbindService() method.
The Android system invokes this method when all the clients
onUnbind() get disconnected from a particular service interface.
Once all clients are disconnected from the particular interface of service and
there is a need to connect the service with new clients, the system calls this
onRebind() method.
activity_main.xml
Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.androidservice.MainActivity">
<Button
android:id="@+id/buttonStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Start Service" />
<Button
android:id="@+id/buttonStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Stop Service" />
<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Next Page" />
</RelativeLayout>
Service class
Now create the service implemenation class by inheriting the Service class and overridding its callback
methods.
File: MyService.java
1. package example.javatpoint.com.androidservice;
2.
3. import android.app.Service;
4. import android.content.Intent;
5. import android.media.MediaPlayer;
6. import android.os.IBinder;
7. import android.support.annotation.Nullable;
8. import android.widget.Toast;
9.
10. public class MyService extends Service {
11. MediaPlayer myPlayer;
12. @Nullable
13. @Override
14. public IBinder onBind(Intent intent) {
15. return null;
16. }
17. @Override
18. public void onCreate() {
19. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
20.
21. myPlayer = MediaPlayer.create(this, R.raw.sun);
22. myPlayer.setLooping(false); // Set looping
23. }
24. @Override
25. public void onStart(Intent intent, int startid) {
26. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
27. myPlayer.start();
28. }
29. @Override
30. public void onDestroy() {
31. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
32. myPlayer.stop();
33. }
34. }
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 example.javatpoint.com.androidservice;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
10. Button buttonStart, buttonStop,buttonNext;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. buttonStart = findViewById(R.id.buttonStart);
17. buttonStop = findViewById(R.id.buttonStop);
18. buttonNext = findViewById(R.id.buttonNext);
19.
20. buttonStart.setOnClickListener(this);
21. buttonStop.setOnClickListener(this);
22. buttonNext.setOnClickListener(this);
23.
24.
25. }
26. public void onClick(View src) {
27. switch (src.getId()) {
28. case R.id.buttonStart:
29.
30. startService(new Intent(this, MyService.class));
31. break;
32. case R.id.buttonStop:
33. stopService(new Intent(this, MyService.class));
34. break;
35. case R.id.buttonNext:
36. Intent intent=new Intent(this,NextPage.class);
37. startActivity(intent);
38. break;
39. }
40. }
41. }
NextPage class
File: NextPage.java
package example.javatpoint.com.androidservice;
1.
2. import android.support.v7.app.AppCompatActivity;
3. import android.os.Bundle;
4.
5. public class NextPage extends AppCompatActivity {
6.
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_next);
11. }
12. }
Declare the Service in the AndroidManifest.xml file
ile: AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/
android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidservice.NextPage">
8.
9. <TextView
10. android:id="@+id/textView"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="200dp"
16. android:text="Next Page"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintStart_toStartOf="parent"
19. app:layout_constraintTop_toTopOf="parent" />
20. </android.support.constraint.ConstraintLayout>
Sensors
Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental condition. The android platform supports three broad categories of sensors.
Motion Sensors
Environmental sensors
Position sensors
Some of the sensors are hardware based and some are software based sensors. Whatever the
sensor is, android allows us to get the raw data from these sensors and use it in our application. For
this android provides us with some classes.
Generally, most of the android devices have built-in sensors to measure motion, orientation, and
various environmental conditions. These sensors will provide raw data with high accuracy and are
useful to monitor three-dimensional device movement or positioning or monitor changes in the
ambient environment near a device.
For example, to report changes in the environment a weather application might use a temperature
sensor and humidity sensor or a travel application might use the geomagnetic field sensor and
accelerometer to report a compass bearing, etc.
The android mainly supports three categories of sensors those are,
Category Description
Motion Sensors These sensors are useful to measure acceleration forces and rotational forces along
three axes. This category includes accelerometers, gravity sensors, gyroscopes, and
rotational vector sensors.
Environmental These sensors are useful to measure various environmental parameters, such as
Sensors ambient air temperature and pressure, illumination, and humidity. This category
includes barometers, photometers, and thermometers.
Position Sensors These sensors are useful to measure the physical position of a device. This category
includes orientation sensors and magnetometers.
Android provided a framework called sensor framework to access all the sensors available on device and to get all
the raw sensor data. The sensor framework provided a wide variety of sensor-related tasks. For example, by using
a sensor framework we can perform the following things
The Android sensor framework will allow us to access many types of sensors, some of these sensors are hardware-
based and some are software-based. The Hardware-based sensors are physical components built on the handset or
tablet device and Software-based sensors are not physical devices but they mimic Hardware-based sensors.
The Android sensor framework provided the following classes and interfaces to access device sensors and acquire
raw sensor data.
Class Description
SensorManager By using this class we can create an instance of sensor service and this class provides a
various methods for accessing and listing sensors, registering and unregistering sensor
event listeners and acquiring orientation information.
Sensor By using this class we can create an instance of a specific sensor and this class provides
various methods that let you determine the sensor's capabilities.
SensorEvent The system uses this class to create a sensor event object and it provides the raw
sensor data, type of sensor that generated the event, accuracy of the data, and the
timestamp for the event.
SensorEventListene We can use this interface to create two callback methods that receive notifications
r (sensor events) when sensor values change or when sensor accuracy changes.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="@+id/sensorslist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Sensors"
android:textSize="20dp"
android:textStyle="bold"
android:layout_gravity="center"
android:visibility="gone"/>
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.sensorsexample path and write the
code like as shown below
MainActivity.java
package com.tutlane.sensorsexample;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private SensorManager mgr;
private TextView txtList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
txtList = (TextView)findViewById(R.id.sensorslist);
List<Sensor> sensorList = mgr.getSensorList(Sensor.TYPE_ALL);
StringBuilder strBuilder = new StringBuilder();
for(Sensor s: sensorList){
strBuilder.append(s.getName()+"\n");
}
txtList.setVisibility(View.VISIBLE);
txtList.setText(strBuilder);
}
}
If you observe above code, we used SensorManager class to identify and get the list of available sensors on a
device.
1. By Camera Intent
2. By Camera API
Intent
By the help of 2 constants of MediaStore class, we can capture picture and video without using the
instance of Camera class.
1. ACTION_IMAGE_CAPTURE
2. ACTION_VIDEO_CAPTURE
Camera
It is main class of camera api, that can be used to take picture and video.
SurfaceView
MediaRecorder
It is used to record video using camera. It can also be used to record audio files as we have seen in
the previous example of media framework.
Drag one imageview and one button from the pallete, now the xml file will look like this:
File: activity_main.xml
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.
1. public void startActivityForResult (Intent intent, int requestCode)
2. public void startActivityForResult (Intent intent, int requestCode, Bundle options)
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/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>
Activity class
Let's write the code to capture image using camera and displaying it on the image view.
File: MainActivity.java
1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;
15. public void onCreate(Bundle savedInstanceState) {
16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }
Bluetooth
Bluetooth is a way to send or receive data between two different devices. Android platform includes
support for the Bluetooth framework that allows a device to wirelessly exchange data with other
Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
Scan for other Bluetooth devices
Get a list of paired devices
Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this
calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant
ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Apart from this constant, there are other constants provided the API , that supports different tasks.
They are listed below.
ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices()
method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth. They are listed below.
1 enable()
This method enables the adapter if not enabled
isEnabled()
2
This method returns true if adapter is enabled
disable()
3
This method disables the adapter
getName()
4
This method returns the name of the Bluetooth adapter
setName(String name)
5
This method changes the Bluetooth name
getState()
6
This method returns the current state of the Bluetooth Adapter.
startDiscovery()
7
This method starts the discovery process of the Bluetooth for 120 seconds.
Example
This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show
list of paired devices by the Bluetooth.
To experiment with this example , you need to run this on an actual device.
Steps Description
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
5 Run the application and choose a running android device and install the application on it
and verify the results.
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends Activity {
Button b1,b2,b3,b4;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}
lv.setAdapter(adapter);
}
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_toStartOf="@+id/imageView"
android:layout_toLeftOf="@+id/imageView"
android:clickable="true"
android:onClick="on" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get visible"
android:onClick="visible"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List devices"
android:onClick="list"
android:id="@+id/button3"
android:layout_below="@+id/imageView"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="turn off"
android:onClick="off"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_below="@+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView2"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button4"
android:layout_alignLeft="@+id/listView"
android:layout_alignStart="@+id/listView" />
</RelativeLayout>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
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>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from Android studio, open one of your project's activity files and
click Run icon from the tool bar.If your Bluetooth will not be turned on then, it will ask your
permission to enable the Bluetooth.
Now just select the Get Visible button to turn on your visibility. The following screen would appear
asking your permission to turn on discovery for 120 seconds.
Now just select the List Devices option. It will list down the paired devices in the list view. In my
case , I have only one paired device. It is shown below.
Now just select the Turn off button to switch off the Bluetooth. Following message would appear
when you switch off the bluetooth indicating the successful switching off of Bluetooth.
Animation in Android with Example
Animation is the process of adding a motion effect to any view, image, or text. With the help
of an animation, you can add motion or can change the shape of a specific view. Animation
in Android is generally used to give your UI a rich look and feel. The animations are
basically of three types as follows:
1. Property Animation
2. View Animation
3. Drawable Animation
1. Property Animation
Property Animation is one of the robust frameworks which allows animating almost
everything. This is one of the powerful and flexible animations which was introduced in
Android 3.0. Property animation can be used to add any animation in
the CheckBox, RadioButtons, and widgets other than any view.
2. View Animation
View Animation can be used to add animation to a specific view to perform tweened
animation on views. Tweened animation calculates animation information such as size,
rotation, start point, and endpoint. These animations are slower and less flexible. An
example of View animation can be used if we want to expand a specific layout in that place
we can use View Animation. The example of View Animation can be seen in Expandable
RecyclerView.
3.Drawable Animation
Drawable Animation is used if you want to animate one image over another. The simple way
to understand is to animate drawable is to load the series of drawable one after another to
create an animation. A simple example of drawable animation can be seen in many apps
Splash screen on apps logo animation.
Methods Description
clearAnimation() This method will clear the animation running on a specific view.
<VideoView
android:id="@+id/simpleVideoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Table Of Contents [hide]
1 Methods Used in VideoView:
2 MediaController In VideoView
3 VideoView Example In Android Studio:
package abhiandroid.com.videofromwebsource;
import android.app.ProgressDialog;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.VideoView;
5. canPause(): This method will tell whether VideoView is able to pause the video. This method
returns a Boolean value means either true or false. If a video can be paused then it returns true
otherwise it returns false.
Below we checks whether a video is able to pause or not.
VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video
view
Boolean canPauseVideo = simpleVideoView.canPause(); // check whether a video is able to pause or
not
6. canSeekForward(): This method will tell whether video is able to seek forward. This method
returns a Boolean value i.e. true or false. If a video can seek forward then it returns true otherwise it
returns false.
Below we checks whether a video is able to seek forward or not.
7. canSeekBackward(): This method will tell whether video is able to seek backward. This method
returns a Boolean value i.e. true or false. If a video can seek backward then it return true otherwise it
return false.
Below we checks whether a video is able to seek backward or not.
8. getDuration(): This method is used to get the total duration of VideoView. This methods return an
integer value.
Below we get the total duration of a video view.
9. getCurrentPosition(): This method is used to get the current position of playback. This method
returns an integer value.
Below we get the current position of a playback.
10. isPlaying(): This method tells whether a video is currently playing or not. This method returns a
Boolean value. It returns true if video is playing or false if it’s not.
Below we check whether a video view is currently playing or not
VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video
view
Boolean isPlaying = simpleVideoView.isPlaying(); // check whether a video view is currently
playing or not
}
});
MediaController In VideoView
MediaController is a class which is used to provide the controls for the video playback. If a video is
simply played using the VideoView class then the user will not be given any control over the playback
of the video which will run until the end of the video is reached. This issue can be addressed by
attaching an instance of the MediaController class to the VideoView instance. The Media Controller
will then provide a set of controls allowing the user to manage the playback (such as seeking
backwards/forwards and pausing in the video timeline).
Methods Of MediaController:
Let’s we discuss some important methods of MediaController class that may be called in order to
control for the playback.
1. setAnchorView(View view): setAnchorView is used to designates the view to which the controller
is to be anchored. This controls the location of the controls on the screen.
Below we show how to use setanchorview() method of a MediaController class.
3. show(int timeout): This method is used to set the time to show the controller on the screen.
Below we set the time for showing the controller on the screen.
5. isShowing(): This method returns a Boolean value indicating whether the controls are currently
visible to the user or not.
Below we checks whether the controls are currently visible or not.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<VideoView
android:id="@+id/simpleVideoView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step 3: Open src -> package -> MainActivity.java
In this step we open MainActivity and add the code to initiate the video view and create an object of
MediaController to control the video playback.
In this class we also set the uri for the video and perform set on error and completion listener events
and display Toast message when video is completed or an error is occur while playing thee video.
Also make sure to create a new directory in res folder and name it raw. Save a video name fishvideo
in raw folder. We will be setting path to this Video in setVideoURI() method.
package example.abhiandroid.videoviewexample;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
VideoView simpleVideoView;
MediaController mediaControls;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find your VideoView in your video_main.xml layout
simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView);
if (mediaControls == null) {
// create an object of media controller class
mediaControls = new MediaController(MainActivity.this);
mediaControls.setAnchorView(simpleVideoView);
}
// set the media controller for video view
simpleVideoView.setMediaController(mediaControls);
// set the uri for the video view
simpleVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.fishvideo));
// start a video
simpleVideoView.start();
Output:
Now run the App and you will see Video playing as the App open. Click on the Video and Media
Controller will appear on the screen.
Android - Text To Speech
Android allows you convert your text into voice. Not only you can convert it but it also allows you to
speak text in variety of different languages.
Android provides TextToSpeech class for this purpose. In order to use this class, you need to
instantiate an object of this class and also specify the initListener. Its syntax is given below −
private EditText write;
ttobj=new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
}
});
In this listener, you have to specify the properties for TextToSpeech object , such as its
language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given
below −
ttobj.setLanguage(Locale.UK);
The method setLanguage takes an Locale object as parameter. The list of some of the locales
available are given below −
Sr.No Locale
1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA
Once you have set the language, you can call speak method of the class to speak the text. Its
syntax is given below −
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
Apart from the speak method, there are some other methods available in the TextToSpeech class.
They are listed below −
Sr.No Method & description
1
addSpeech(String text, String filename)
This method adds a mapping between a string of text and a sound file.
2
getLanguage()
This method returns a Locale instance describing the language.
3
isSpeaking()
This method checks whether the TextToSpeech engine is busy speaking.
4
setPitch(float pitch)
This method sets the speech pitch for the TextToSpeech engine.
5
setSpeechRate(float speechRate)
This method sets the speech rate.
6
shutdown()
This method releases the resources used by the TextToSpeech engine.
7
stop()
This method stop the speak.
Example
The below example demonstrates the use of TextToSpeech class. It crates a basic application that
allows you to set write text and speak it.
To experiment with this example , you need to run this on an actual device.
Steps Description
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.
4 Run the application and choose a running android device and install the application on it and
verify the results.
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
Toast.makeText(getApplicationContext(),
toSpeak,Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageView"
android:layout_marginTop="46dp"
android:hint="Enter Text"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ff7aff10"
android:textColorHint="#ffff23d1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to Speech"
android:id="@+id/button"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
</RelativeLayout>
<activity
android:name=".MainActivity"
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>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from Android studio, open one of your project's activity files and
click Run icon from the toolbar. Before starting your application, android studio will display
following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display
following screen.
Now just type some text in the field and click on the text to speech button below. A notification would
appear and text will be spoken. It is shown in the image below −
Now type something else and repeat the step again with different locale. You will again hear sound.
This is shown below −