And Unit 5
And Unit 5
Types of Intent:
1. Implicit Intent
2. Explicit Intent
1. Implicit Intent
It doesn't specify the component. In such case, intent provides information of available
components provided by the system that is to be invoked.
An Implicit intent allows you start an activity in another app by describing an action you
intend to perform such as View a map, take a picture
For example, you may write the following code to view the webpage.
1. Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to
be invoked.
It is used to launch a specific app component
Example
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
1
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Write a Program to Implement Implicit & Explicit Intent
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent"/>
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent"/>
</LinearLayout>
MainActivity.java
package com.example.intentprogram;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.google.com"));
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
2
Mobile Application Development 5th Unit P.S.Gaidhani
{
Intent i=new Intent(getApplicationContext(),SecondActivity.class);
startActivity(i);
}
});
}
}
4 Action It represent an activities action, what an activity is going to do. It is declared with
the name attribute as given below
<action android:name="android.intent.action.MAIN" />
5 Categeory We will make an activity a launcher activity by declaring intent filter.
Laucher means this activity will be launched first out of all activities in
application
<category android:name="android.intent.category.LAUNCHER" />
Data There are two forms in which you can pass the data, using URI(Uniform
Resource Identifiers) or MIME type of data.
<data android:scheme="string"
android:host="string"
3
Mobile Application Development 5th Unit P.S.Gaidhani
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
This specifies the format of data associated with an Intent which you use with
component. As explained in above code snippet, data passed through Intent is a
type of URI.
4
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Define Activity and Draw Lifecycle of an activity
An Android activity is one screen of the Android app's user interface. In that way an
Android activity is very similar to windows in a desktop application.
An Android app may contain one or more activities, meaning one or more screens.
The Android app starts by showing the main activity, and from there the app may make it
possible to open additional activities.
5
Mobile Application Development 5th Unit P.S.Gaidhani
onStart called when activity is public void onStart()
becoming visible to the user. {
Super.onStart();
}
package com.example.activitylifecycle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
6
Mobile Application Development 5th Unit P.S.Gaidhani
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
7
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Define Broadcast in Android with its two types
Broadcast Intents
o We required third type of Intent that can be delivered to any application known as
Broadcast intent
o A broadcast intent is a background operation,on the other hand is a foreground
operation that modifies what the user currently interacting with
android.intent.action.BATTERY_CHANGED
1
Sticky broadcast containing the charging state, level, and other information about the
battery.
android.intent.action.BATTERY_LOW
2
Indicates low battery condition on the device.
android.intent.action.BATTERY_OKAY
3
Indicates the battery is now okay after being low.
android.intent.action.BOOT_COMPLETED
4
This is broadcast once, after the system has finished booting.
android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.
android.intent.action.CALL
6
Perform a call to someone specified by the data.
android.intent.action.CALL_BUTTON
7 The user pressed the "call" button to go to the dialer or other appropriate UI for placing a
call.
8
Mobile Application Development 5th Unit P.S.Gaidhani
android.intent.action.DATE_CHANGED
8
The date has changed.
android.intent.action.REBOOT
9
Have the device reboot.
This intent ggsp.CUSTOM_INTENT can also be registered in similar way as we have regsitered system
generated intent.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="ggsp.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
9
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Explain Broadcast Receivers in Android
Broadcast Receivers simply respond to broadcast messages from other applications or from the system
itself. These messages are sometime called events or intents.
There are following two important steps to make BroadcastReceiver works for the system broadcasted
intents −
Creating the Broadcast Receiver.
Registering Broadcast Receiver
Broadcast-Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
10
Mobile Application Development 5th Unit P.S.Gaidhani
</receiver>
</application>
Q. Define Content Provider
In android, Content Provider will act as a central repository to store the data of the application in one
place and make that data available for different applications to access whenever it’s required.
A Content provider:
Separate data from the app code interface
Provide standard way for accessing the data
Makes it possible to share the data with other applications
ont
ent
pro
vid
ers
let
you
cen
tral
ize
con
tent
in
one
pla
ce and have many different applications access it as needed.
A content provider behaves very much like a database where you can query it, edit its
content, as well as add or delete content using insert(), update(), delete(), and query()
methods.
In most cases this data is stored in an SQlite database.
11
Mobile Application Development 5th Unit P.S.Gaidhani
Content URIs
To query a content provider, you specify the query string in the form of a URI which has following
format −
<prefix>://<authority>/<data_type>/<id>
Here is the detail of various parts of the URI −
1 prefix
This is always set to content://
authority
2 This specifies the name of the content provider, for example contacts, browser etc. For third-
party content providers, this could be the fully qualified name
data_type
This indicates the type of data that this particular provider provides. For example, if you are
3 getting all the contacts from the Contacts content provider, then the data path would
be people and URI would look like this
Ex. content://contacts/people
id
This specifies the specific record requested. For example, if you are looking for contact number
4 5 in the Contacts content provider then URI would look like this
content://contacts/people/5.
12
Mobile Application Development 5th Unit P.S.Gaidhani
Q. How to create Content Provider
This involves number of simple steps to create your own content provider.
Step1: Create a class which will extends from ContentProvider Class
}
Step2: Define your content provider URI address which will be used to access the content.
<prefix>://<authority>/<data_type>/<id>
Step3:
Next you will need to create your own database to keep the content.
Usually, Android uses SQLite database and framework needs to override onCreate() method
which will use SQLite Open Helper method to create or open the provider's database.
When your application is launched, the onCreate() handler of each of its Content Providers is
called on the main application thread.
Step4: Next you will have to implement Content Provider queries to perform different database specific
operations.
Step5: Finally register your Content Provider in your activity file using <provider> tag.
Here is the list of methods which you need to override in Content Provider class to have your Content
Provider working −
13
Mobile Application Development 5th Unit P.S.Gaidhani
update() This method updates an existing record from the content provider.
getType() This method returns the MIME type of the data at the given URI.
14
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Draw & Explain Fragment LifeCycle in Android
15
Mobile Application Development 5th Unit P.S.Gaidhani
4) onActivityCreated(Bundle) It is invoked after the completion of onCreate()
method.
3. Fragments transaction
Using with fragment transaction. We can move one fragment to another fragment.
16
Mobile Application Development 5th Unit P.S.Gaidhani
Program to implement Fragments in Android
activity_main.xml
Note:Add fragment tag in xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity">
<fragment
android:id="@+id/fragment1"
android:name="com.example.myapplicationfragment.Fragment1Activity"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"/>
<fragment
android:id="@+id/fragment2"
android:name="com.example.myapplicationfragment.Fragment2Activity"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
17
Mobile Application Development 5th Unit P.S.Gaidhani
activity_fragment2.xml
Fragment1Activity.java
package com.example.myapplicationfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_fragment1, container, false);
}
}
Fragment2Activity.java
package com.example.myapplicationfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
18
Mobile Application Development 5th Unit P.S.Gaidhani
import android.view.View;
import android.view.ViewGroup;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_fragment2, container, false);
}
}
MainActivity.java
package com.example.myapplicationfragment;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
19
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Explain Services in Android
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).
Features of Service:
1. Android services interface interprets real world actions like swipping,tapping,pinching and reverse
pinching to work the objects appearing on the mobile screen with the help of virtual keyboard
2. Internal hardware applications have been built to adjust and manipulate the screen according to the
need of the user
3. Ex. While watching a video or playing game you can enable the rotate screen feature i.e on the
landscape mode
There can be two forms of a service. The lifecycle of service can follow two different paths: started or
bound.
1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it runs in the
background indefinitely. It is stopped by stopService() metho d. The service can stop itself by calling
the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. The client can
unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
20
Mobile Application Development 5th Unit P.S.Gaidhani
Sr.No. Callback & Description
1
onStartCommand()
The system calls this method when another component, such as an activity, requests that
the service be started, by calling startService(). If you implement this method, it is your
responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.
2
onBind()
The system calls this method when another component wants to bind with the service by
calling bindService(). If you implement this method, you must provide an interface that
clients use to communicate with the service, by returning an IBinder object. You must
always implement this method, but if you don't want to allow binding, then you should
return null.
3
onUnbind()
The system calls this method when all clients have disconnected from a particular interface
published by the service.
21
Mobile Application Development 5th Unit P.S.Gaidhani
4
onRebind()
The system calls this method when new clients have connected to the service, after it had
previously been notified that all had disconnected in its onUnbind(Intent).
5
onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-up.
6
onDestroy()
The system calls this method when the service is no longer used and is being destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, receivers, etc.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:text="Start Service"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/b2"
android:text="Stop Service"/>
<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Page" />
</LinearLayout>
22
Mobile Application Development 5th Unit P.S.Gaidhani
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.videoplayer">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true" />
</application>
</manifest>
MyService.java
package com.example.myapplication;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
23
Mobile Application Development 5th Unit P.S.Gaidhani
//intent (StartService Intent,flags Additional data about this start Requested,Unique integer representing
request to start
public int onStartCommand(Intent intent, int flags, int startId) {
m1 = MediaPlayer.create(this,R.raw.dil);
// This will play the ringtone continuously until we stop the service.
m1.setLooping(true);
// It will start the player
m1.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
// tells the system to create fresh copy of the service when sufficient menory is avaliable after it
recovers from low memory
}
public void onDestroy()
{
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
m1.stop();
}
}
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button b1,b2,b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
b3=findViewById(R.id.b3);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this,MyService.class);
startService(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this,MyService.class);
stopService(i);
24
Mobile Application Development 5th Unit P.S.Gaidhani
}
});
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this,second.class);
startActivity(i);
}
})
;
}
}
25
Mobile Application Development 5th Unit P.S.Gaidhani
Multimedia Framework
Q. Explain Media Player in Android with program
MediaPlayer
Android is providing MediaPlayer class to access built-in mediaplayer services like playing
audio,video e.t.c.
In order to use MediaPlayer, we have to call a static Method create() of this class.
Syntax:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
The second parameter is the name of the song that you want to play. You have to make a new
folder under your project with name raw and place the music file into it.
Once you have created the Mediaplayer object you can call some methods to start or stop the
music. These methods are listed below.
mediaPlayer.start();
mediaPlayer.pause();
In order to start music from the beginning, you have to call reset() method. Its syntax is given
below.
mediaPlayer.reset();
Apart from the start and pause method, there are other methods provided by this class for better dealing
with audio/video files. These methods are listed below −
1
isPlaying()
This method just returns true/false indicating the song is playing or not
2
seekTo(position)
This method takes an integer, and move song to that particular position millisecond
3
getCurrentPosition()
This method returns the current position of song in milliseconds
4
getDuration()
This method returns the total time duration of song in milliseconds
26
Mobile Application Development 5th Unit P.S.Gaidhani
5
reset()
This method resets the media player
6
release()
This method releases any resource attached with MediaPlayer object
7
setVolume(float leftVolume, float rightVolume)
This method sets the up down volume for this player
8
setDataSource(FileDescriptor fd)
This method sets the data source of audio/video file
9
selectTrack(int index)
This method takes an integer, and select the track from the list on that particular index
10
getTrackInfo()
This method returns an array of track information
Program:
27
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Explain Video Player in Android
we can play the video files in android by the help of
1. MediaController Class &
2. VideoView Class
MediaController class
The android.widget.MediaController is a view that contains media controls like play/pause, previous,
next, fast-forward, rewind etc.
Methods
VideoView class
The android.widget.VideoView class provides methods to play and control the video player. The
commonly used methods of VideoView class are as follows:
Method Description
public void setVideoURI (Uri uri) sets the URI of the video file.
28
Mobile Application Development 5th Unit P.S.Gaidhani
Program to play video in android
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<VideoView
android:layout_width="400dp"
android:layout_height="400dp"
android:id="@+id/v1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="@+id/b1"
android:layout_gravity="center"
android:layout_marginTop="10dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:id="@+id/b2"
android:layout_gravity="center"
android:layout_marginTop="10dp"/>
</LinearLayout>
MainActivity.java
package com.example.videoplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
29
Mobile Application Development 5th Unit P.S.Gaidhani
import android.widget.Toast;
import android.widget.VideoView;
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MediaController mediaController=new MediaController(MainActivity.this);
v1.setMediaController(mediaController);
mediaController.setAnchorView(v1);
30
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Program to implement Text to Speech in 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.
Step1:
Need to implement
1. TextToSpeech Class &
2. TextToSpeech.OnInitListener()
Its syntax is given below −
Step2:
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
31
Mobile Application Development 5th Unit P.S.Gaidhani
Step3:
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 −
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.
32
Mobile Application Development 5th Unit P.S.Gaidhani
Program to text to speech in android
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter the text"
android:id="@+id/e1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:text="Text To Speech"/>
</LinearLayout>
MainActivity.java
package com.example.myapplicationtexttospeech;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
{
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.e1);
b1=(Button)findViewById(R.id.b1);
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
33
Mobile Application Development 5th Unit P.S.Gaidhani
@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);
}
});
}
}
34
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Define Sensors with its types
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device
Android provides sensor API to work with different types of sensors.
Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental condition
Types of Sensors
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
2) Position Sensors
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
Step2:
The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor()
method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Step3:
Once that sensor is declared , you need to register its listener and override two methods which are
onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
public void onSensorChanged(SensorEvent event) { }
35
Mobile Application Development 5th Unit P.S.Gaidhani
Example: Program to implement Sensors
Program
Activity_main.XML
<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
/>
</LinearLayou>
MainActivity.java
package com.example.myapplicationsensor;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.util.EventListener;
import java.util.List;
}
public void onSensorChanged(SensorEvent event)
36
Mobile Application Development 5th Unit P.S.Gaidhani
{
float[] values = event.values;
textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView)findViewById(R.id.t1);
list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(list.size()>0){
sm.registerListener(sel, (Sensor) list.get(0),
SensorManager.SENSOR_DELAY_NORMAL);
}else{
Toast.makeText(getBaseContext(), "Error: No Accelerometer.",
Toast.LENGTH_LONG).show();
}
}
@Override
protected void onStop() {
if(list.size()>0){
sm.unregisterListener(sel);
}
super.onStop();
}
}
37
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Write a program to capture an image using camera and display it.
In android, Camera is useful to capture the photos and videos in our applications. By using camera API
we can control the functionalities of camera based on our requirements.
The android framework provides a two ways to capture images and videos in our application
1. android.hardware.camera2 API
It’s a primary API for controlling the device cameras. By using this we can take the
pictures or videos from our application using camera
2. Camera Intent
By using Intent
MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_VIDEO_CAPTURE,
we can capture the photos or videos without directly using the Camera object.
The best way is to use an intent to invoke an existing Android camera application to take pictures
or videos in our application without writing a lot of extra code.
Syntax:
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
used startActivityForResult() method
o First Parameter:with MediaStore.ACTION_IMAGE_CAPTURE intent action
parameter to capture the photos.
o The second parameter Image_Capture_Code is a locally defined integer that must be
greater than 0.
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Take a Photo" >
</Button>
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/button1"
android:layout_alignParentTop="true”>
</ImageView>
38
Mobile Application Development 5th Unit P.S.Gaidhani
</RelativeLayout>
MainActivity.java
package com.example.myapplicationcamera;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
39
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Explain Bluetooth in Android with example
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
Step1:
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.
BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
Step2:
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant
ACTION_REQUEST_ENABLE. Its syntax is.
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
Step3:
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();
40
Mobile Application Development 5th Unit P.S.Gaidhani
Apart form the parried devices , there are other methods in the API that gives more control over
bluetooth. 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.
41
Mobile Application Development 5th Unit P.S.Gaidhani
Program of Bluetooth
Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<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"
42
Mobile Application Development 5th Unit P.S.Gaidhani
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" />
</LinearLayout>
myapplicationblutooth .java
package com.example.myapplicationblutooth;
import androidx.appcompat.app.AppCompatActivity;
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;
@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);
43
Mobile Application Development 5th Unit P.S.Gaidhani
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView) findViewById(R.id.listView);
}
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
lv.setAdapter(adapter);
}
}
44
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Explain Animation in Android with example
Animation in android is possible from many ways. In this chapter we will discuss one easy and widely
used way of making animation called tweened animation.
Tween Animation
Tween Animation takes some parameters such as start value, end value, size, time duration, rotation angle
e.t.c and performs the required animation on that object. It can be applied to any type of object. So in
order to use this, android has provided us a class called Animation.
1 start()
This method starts the animation.
setDuration(long duration)
2
This method sets the duration of an animation.
getDuration()
3
This method gets the duration which is set by above method
end()
4
This method ends the animation.
cancel()
5
This method cancels the animation.
45
Mobile Application Development 5th Unit P.S.Gaidhani
Step2
In order to apply this animation to an object, we will just call the startAnimation() method of the object.
Its syntax is −
Program of Animation
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=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Animation in Android"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@mipmap/ic_launcher_round"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="zoom"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:onClick="clockwise"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="clockwise"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
46
Mobile Application Development 5th Unit P.S.Gaidhani
android:onClick="zoom"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fade"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="fade"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blink"
android:onClick="blink"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="move"
android:onClick="move"
android:id="@+id/button5"
android:layout_below="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="slide"
android:onClick="slide"
android:id="@+id/button6"
android:layout_below="@+id/button3"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />
</RelativeLayout>
MainActivity.java
package com.example.myapplicationanimation;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
47
Mobile Application Development 5th Unit P.S.Gaidhani
public void zoom(View view){
ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.clockwise);
image.startAnimation(animation1);
}
1. Animation.xml
2. <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="3.0"
android:fromYScale="0.5"
android:toYScale="3.0"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
48
Mobile Application Development 5th Unit P.S.Gaidhani
android:fromXScale="3.0"
android:toXScale="0.5"
android:fromYScale="3.0"
android:toYScale="0.5"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
</set>
2.clockwise.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
</set>
3.fade.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator" >
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000" >
</alpha>
<alpha
android:startOffset="2000"
android:fromAlpha="1"
android:toAlpha="0"
android:duration="2000" >
</alpha>
</set>
4.blink,xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="600"
49
Mobile Application Development 5th Unit P.S.Gaidhani
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
5.move.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
6.slide.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
50
Mobile Application Development 5th Unit P.S.Gaidhani