0% found this document useful (0 votes)
147 views

Activity Lifecycle With Example in Android

Android intents allow communication between app components like activities, services, and content providers. There are two main types: implicit intents specify an action without a specific component, while explicit intents call a specific component class. The document provides examples of using implicit intents to launch a web browser and explicit intents to start a new activity and pass data between activities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

Activity Lifecycle With Example in Android

Android intents allow communication between app components like activities, services, and content providers. There are two main types: implicit intents specify an action without a specific component, while explicit intents call a specific component class. The document provides examples of using implicit intents to launch a web browser and explicit intents to start a new activity and pass data between activities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

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:

o Start the service


o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o 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. <?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. }  

   

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


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.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.

Intent Filter in Manifest File 


Following is the code snippet of defining an activity with Intent Filter (<intent-filter>) in the Android Manifest file
(AndroidManifest.xml) like as shown below.
 
<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>
We can define a filter with multiple instances of <action>, <category> or <data> elements and we need to make
sure that component can handle all the combinations of filter elements.

   

Activity Lifecycle With Example In Android – Tutorial, Code And Importance


Activity Lifecycle: Activity is one of the building blocks of Android OS. In simple words Activity is a screen
that user interact with. Every Activity in android has lifecycle like created, started, resumed, paused, stopped or
destroyed. These different states are known as Activity Lifecycle. In other words we can say Activity is a class
pre-written in Java Programming.
Below is Activity Lifecycle Table:
Short description of Activity Lifecycle example:
onCreate() – Called when the activity is first created
onStart() – Called just after it’s creation or by restart method after onStop(). Here Activity start
becoming visible to user
onResume() – Called when Activity is visible to user and user can interact with it
onPause() – Called when Activity content is not visible because user resume previous activity
onStop() – Called when activity is not visible to user because some other activity takes place of it
onRestart() – Called when user comes on screen or resume the activity which was stopped
Below Activity Lifecycle Diagram Shows Different States:

Different Types of Activity Lifecycle States:


Activity have different states or it’s known as Activity life cycle. All life cycle methods aren’t required to
override but it’s quite important to understand them. Lifecycles methods can be overridden according to
requirements.
LIST OF ACTIVITY LIFECYCLE METHODS OR STATES:
Activity Created: onCreate(Bundle savedInstanceState):
onCreate() method is called when activity gets memory in the OS. To use create state we need to override
onCreate(Bundle savedInstanceState) method. Now there will be question in mind what is Bundle here, so
Bundle is a data repository object that can store any kind of primitive data and this object will be null until some
data isn’t saved in that.
 When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible
to create the activity.
 When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed
or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e.
object of Bundle Class will save the state of an Activity.
 It is best place to put initialization code.
Learn More About onCreate(Bundle savedInstanceState) With Example
Activity Started: onStart():
onStart() method is called just after it’s creation. In other case Activity can also be started by calling restart
method i.e after activity stop. So this means onStart() gets called by Android OS when user switch between
applications. For example, if a user was using Application A and then a notification comes and user clicked on
notification and moved to Application B, in this case Application A will be paused. And again if a user again
click on app icon of Application A then Application A which was stopped will again gets started.
Learn More About onStart() With Example
Activity Resumed:.onResume():
Activity resumed is that situation when it is actually visible to user means the data displayed in the activity is
visible to user. In lifecycle it always gets called after activity start and in most use case after activity paused
(onPause).
Activity Paused: onPause():
Activity is called paused when it’s content is not visible to user, in most case onPause() method called by
Android OS when user press Home button (Center Button on Device) to make hide.
Activity also gets paused before stop called in case user press the back navigation button. The activity will go in
paused state for these reasons also if a notification or some other dialog is overlaying any part (top or bottom) of
the activity (screen). Similarly, if the other screen or dialog is transparent then user can see the screen but
cannot interact with it. For example, if a call or notification comes in, the user will get the opportunity to take
the call or ignore it.
Learn More About onPause() With Example
Activity Stopped: onStop():
Activity is called stopped when it’s not visible to user. Any activity gets stopped in case some other activity
takes place of it. For example, if a user was on screen 1 and click on some button and moves to screen 2. In this
case Activity displaying content for screen 1 will be stopped.
Every activity gets stopped before destroy in case of when user press back navigation button. So Activity will
be in stopped state when hidden or replaced by other activities that have been launched or switched by user. In
this case application will not present anything useful to the user directly as it’s going to stop.
Activity Restarted: onRestart():
Activity is called in restart state after stop state. So activity’s onRestart() function gets called when user comes
on screen or resume the activity which was stopped. In other words, when Operating System starts the activity
for the first time onRestart() never gets called. It gets called only in case when activity is resumes after stopped
state.
Activity Destroyed: onDestroy():
Any activity is known as in destroyed state when it’s not in background. There can different cases at what time
activity get destroyed.
First is if user pressed the back navigation button then activity will be destroyed after completing the lifecycle
of pause and stop.
In case if user press the home button and app moves to background. User is not using it no more and it’s being
shown in recent apps list. So in this case if system required resources need to use somewhere else then OS can
destroy the Activity.
After the Activity is destroyed if user again click the app icon, in this case activity will be recreated and follow
the same lifecycle again. Another use case is with Splash Screens if there is call to finish() method from
onCreate() of an activity then OS can directly call onDestroy() with calling onPause() and onStop().
We have used Log class which is used to printout message in Logcat. One of the important use of Log is in
debugging.

 was called when Activity is not in background


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 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

A string that specifies the generic action to perform (such as view or pick).

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.

Types of Android Services

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.

Fundamentals of Android Services


A user-defined service can be created through a normal class which is extending the  class Service. Further, to
carry out the operations of service on applications, there are certain callback methods which are needed to
be overridden. The following are some of the important methods of Android Services:
Methods Description

The Android service calls this method when a component(eg: activity) 


requests to start a service using startService(). Once the service is started,
onStartCommand() it can be stopped explicitly using stopService() or stopSelf() methods.

This method is mandatory to implement in android service and is invoked 


whenever an application component calls the bindService() method in order to
bind itself with a service. User-interface is also provided to communicate 
with the service effectively by returning an IBinder object. 
onBind() If the binding of service is not required then the method must return null.
Methods Description

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.

Whenever a service is created either using onStartCommand() or onBind(),


the android system calls this method. This method is necessary to perform 
onCreate() a one-time-set-up.

When a service is no longer in use, the system invokes this method


 just before the service destroys as a final clean up call. Services must
 implement this method in order to clean up resources like registered listeners,
onDestroy()  threads, receivers, etc.

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

Now, create another activity.

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

Finally, declare the service in the manifest file.

ile: AndroidManifest.xml

Let's see the complete AndroidManifest.xml file


1. <?xml version="1.0" encoding="utf-8"?>  
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
3.     package="example.javatpoint.com.androidservice">  
4.   
5.     <application  
6.         android:allowBackup="true"  
7.         android:icon="@mipmap/ic_launcher"  
8.         android:label="@string/app_name"  
9.         android:roundIcon="@mipmap/ic_launcher_round"  
10.         android:supportsRtl="true"  
11.         android:theme="@style/AppTheme">  
12.         <activity android:name=".MainActivity">  
13.             <intent-filter>  
14.                 <action android:name="android.intent.action.MAIN" />  
15.   
16.                 <category android:name="android.intent.category.LAUNCHER" />  
17.             </intent-filter>  
18.         </activity>  
19.         <activity android:name=".NextPage"></activity>  
20.         <service  
21.             android:name=".MyService"  
22.             android:enabled="true" />  
23.     </application>  
24.   
25. </manifest>  
File: activity_next.xml

It contains only one textview displaying the message Next Page

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
 

 It lists all the available sensors on the device


 It determines the capabilities of each sensor, such as its maximum range, manufacturer, power requirements,
and resolution.
 It can acquire raw sensor data and define the minimum rate at which you acquire sensor data.
 Register and unregister sensor event listeners that monitor sensor changes.

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.

Identify the List of Available Sensors


Following is the code snippet of identifying and listing all the available sensors on a device, checking whether the
specific type of sensor exists or not and monitoring a sensor event changes using android sensor framework classes
in android applications.
 
public class MainActivity extends AppCompatActivity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor sensor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        sensor = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
        List<Sensor> deviceSensors = mgr.getSensorList(Sensor.TYPE_ALL);
    }
    @Override
    public final void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Do something here if sensor accuracy changes.
    }
    @Override
    public final void onSensorChanged(SensorEvent event) {
        // Do something with this sensor value.
    }
    @Override
    protected void onResume() {
        super.onResume();
        mgr.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
}
If you observe above code snippet, we used android sensor framework classes to list all available sensors on a device
and monitoring the sensor event changes based on our requirements.
 
Now we will see how to use android sensor framework to get the list of available sensors on android device with
examples.

Android Sensors Example


Following is the example of identifying the sensors and list all the available sensors on a device using android sensor
framework.
 
Create a new android application using android studio and give names as SensorExample. In case if you are not
aware of creating an app in android studio check this article Android Hello World App.
 
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as
shown below.

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.

Output of Android Sensors Example


When we run the above program in the android studio we will get the result as shown below.
 

Android Camera Tutorial


Camera is mainly used to capture picture and video. We can control the camera by using methods of
camera api.

Android provides the facility to work on camera by 2 ways:

1. By Camera Intent
2. By Camera API

Understanding basic classes of Camera Intent and API


There are mainly four classes that we are going to discuss.

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

It represents a surface view ore preview of live camera.

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.

Android camera app example by camera intent


In this example, we are writing the simple code to capture image using camera and displaying the
image using imageview.
activity_main.xml

Drag one imageview and one button from the pallete, now the xml file will look like this:

File: activity_main.xml

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)  

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. }  

download this android example


Output:

Next Topic Androi

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.

Sr.No Constant & description


1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth

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.

Sr.No Method & description

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

1 You will use Android studio to create an Android application a package


com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add the code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

4 Modify AndroidManifest.xml to add necessary permissions.

5 Run the application and choose a running android device and install the application on it
and verify the results.

Here is the content of src/MainActivity.java


package com.example.sairamkrishna.myapplication;

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);
}

public void on(View v){


if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned
on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on",
Toast.LENGTH_LONG).show();
}
}

public void off(View v){


BA.disable();
Toast.makeText(getApplicationContext(), "Turned off"
,Toast.LENGTH_LONG).show();
}

public void visible(View v){


Intent getVisible = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}

public void list(View v){


pairedDevices = BA.getBondedDevices();

ArrayList list = new ArrayList();

for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());


Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1, list);

lv.setAdapter(adapter);
}
}

Here is the content of activity_main.xml


Here abc indicates about logo of tutorialspoint.
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Bluetooth Example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<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>

Here is the content of Strings.xml


<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<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.

. Important Methods of Animation 

Methods Description

startAnimation() This method will start the animation. 

clearAnimation() This method will clear the animation running on a specific view. 

VideoView Tutorial With Example In Android Studio


In Android, VideoView is used to display a video file. It can load images from various sources (such as
content providers or resources) taking care of computing its measurement from the video so that it
can be used for any layout manager, providing display options such as scaling and tinting.
Important Note: VideoView does not retain its full state when going into the background. In
particular it does not restore the current play position and play state. Applic
Important Note: VideoView does not retain its full state when going into the background. In
particular it does not restore the current play position and play state. Applications should save and
restore these in onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle).
VideoView code In XML Android:

<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:

Methods Used in VideoView:


Let’s we discuss some important methods of VideoView that may be called in order to manage the
playback of video:
1. setVideoUri(Uri uri): This method is used to set the absolute path of the video file which is going to
be played. This method takes a Uri object as an argument.
Below we set the uri of video which is saved in Android Studio:
Step 1: Create a new directory in res folder and name it raw
Step 2: Save a video name fishvideo in raw folder
Step 3: Now use the below code to set the path for the video using setVideoUri() method in
VideoView.

// initiate a video view


VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView);
simpleVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.fishvideo));

Setting Video From Online Web Source:


Step 1: First add internet permision in Manifest.xml file. We will need to add this so as to access the
video through Internet. Open AndroidManifest.xml and add the below code

<!--Add this before application tag in AndroidManifest.xml-->


<uses-permission android:name="android.permission.INTERNET" />

Step 2: Add the basic VideoVideo XML code in activity_main.xml or activity.xml


Step 3: Use the below code to access the Video from our website

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;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("/ui/wp-content/uploads/2016/04/videoviewtestingvideo.mp4");
VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); //
initiate a video view
simpleVideoView.setVideoURI(uri);
simpleVideoView.start();
}
}

2. setMediaController(MediaController controller): This method of VideoView is used to set the


controller for the controls of video playback.
Below we show how to set the media controller object for a video view.

// create an object of media controller


MediaController mediaController = new MediaController(this);
// initiate a video view
VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView);
// set media controller object for a video view
simpleVideoView.setMediaController(mediaController);

3. start(): This method of VideoView is used to start the playback of video file.


Below we show how to start a video in video view.
VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video
view
simpleVideoView.start(); // start a video

4. pause(): This method of video view is used to pause the current playback.


Below we shows how to pause a video in video view.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view
simpleVideoView.pause(); // pause a video

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.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view
Boolean canSeekForward = simpleVideoView.canSeekForward(); // checks whether a video view 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.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view
Boolean canSeekBackword = simpleVideoView.canSeekBackward(); // checks whether a video view is
able to seek backword 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.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view
int duration =simpleVideoView.getDuration();// get the total duration of the video

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.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view
int currentPosition = simpleVideoView.getCurrentPosition(); // get the current position of the
video play back

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

11. stopPlayback(): This method of VideoView is used to stop the video playback.


Below we show how to stop a video in video view.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view
simpleVideoView.stopPlayback(); // stop a video

12. setOnPreparedListener(MediaPlayer.OnPreparedListener): This is a  listener which allows a


callback method to be called when the video is ready to play.
Below we show the use of setOnPreparedListener event of a video view.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view

// perform set on prepared listener event on video view


simpleVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {

// do something when video is ready to play

}
});

13. setOnErrorListener(MediaPlayer.OnErrorListener): This listener allows a callback method to be


called when an error occurs during the video playback.
Below we show the use of setOnErrorListener event of a video view.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view

// perform set on error listener event on video view


simpleVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// do something when an error is occur during the video playback
return false;
}
});

14. setOnCompletionListener(MediaPlayer.OnCompletionListener): This listener allow a callback


method to be called when the end of the video is reached.
Below we shows the use of setOnCompletionListener event of a video view.

VideoView simpleVideoView = (VideoView) findViewById(R.id.simpleVideoView); // initiate a video


view
// perform set on completion listener event on video view
simpleVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// do something when the end of the video is reached
}
});

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.

MediaController mediaController = new MediaController(this); // create an object of media


controller
mediaController.setAnchorView(simpleVideoView); // set anchor view for video view
2. show(): This method is used to show the controller on the screen.
Below we show the controller on the screen.

MediaController mediaController = new MediaController(this); // create an object of media


controller
mediaController.show(); // show the controller on the screen

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.

MediaController mediaController = new MediaController(this); // create an object of media


controller
mediaController.show(500); // set the time to show the controller on the screen

4. hide(): This method is used to hide the controls from the screen.


Below we hide the control from the screen

MediaController mediaController = new MediaController(this); // create an object of media


controller
mediaController.hide(); // hide the control from 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.

MediaController mediaController = new MediaController(this); // create an object of media


controller
Boolean isShowing = mediaController.isShowing(); // checks whether the controls are currently
visible or not

VideoView Example In Android Studio:


Below is the example of VideoView in Android in which we play a video in a video view by using Media
Controller and perform set on error and completion listener events and display Toast when the video
is completed or an error occur while playing thee video.
In this example we create a folder named raw in our project and store the video file in that folder and
then set the uri for the video in our activity in which we display the video view.
Below is the final output, download code and step by step explanation:
Download Code  ?
Step 1: Create a new project in Android Studio and name it VideoViewExample
Step 2: Open res -> layout -> xml (or) main.xml and add following code :
In this step we open an xml file and add the code to display a VideoView in our activity.

<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;

public class MainActivity extends Activity {

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();

// implement on completion listener on video view


simpleVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(getApplicationContext(), "Thank You...!!!",
Toast.LENGTH_LONG).show(); // display a toast when an video is completed
}
});
simpleVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(), "Oops An Error Occur While Playing
Video...!!!", Toast.LENGTH_LONG).show(); // display a toast when an error is occured while playing
an video
return false;
}
});
}

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.

2 Modify src/MainActivity.java file to add TextToSpeech code.


3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

4 Run the application and choose a running android device and install the application on it and
verify the results.

Here is the content of src/MainActivity.java.


package com.example.sairamkrishna.myapplication;

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;

public class MainActivity extends Activity {


TextToSpeech t1;
EditText ed1;
Button b1;

@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);

t1=new TextToSpeech(getApplicationContext(), new


TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});

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);
}
});
}

public void onPause(){


if(t1 !=null){
t1.stop();
t1.shutdown();
}
super.onPause();
}
}

Here is the content of activity_main.xml


In the following code abcindicates the logo of tutorialspoint.com

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


<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Text to Speech" android:layout_width="wrap_content"


android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<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>

Here is the content of Strings.xml.


<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<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 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 −

You might also like