0% found this document useful (0 votes)
22 views50 pages

And Unit 5

Android intents allow communication between app components like activities and services. There are two types of intents: implicit intents specify an action without a specific component, while explicit intents specify a particular component class. An intent is an object containing information about an operation to be performed, like launching an activity. Activities have a lifecycle with callback methods like onCreate that get called as the activity transitions between states like running, paused, and stopped.

Uploaded by

Bilal Pathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views50 pages

And Unit 5

Android intents allow communication between app components like activities and services. There are two types of intents: implicit intents specify an action without a specific component, while explicit intents specify a particular component class. An intent is an object containing information about an operation to be performed, like launching an activity. Activities have a lifecycle with callback methods like onCreate that get called as the activity transitions between states like running, paused, and stopped.

Uploaded by

Bilal Pathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Q. Define Intent with its two type’s .

Explain with Syntax and Example


Intent
 Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc.
 An Android Intent is an abstract description of an operation to be performed
 The intent itself, an Intent object, is a passive data structure holding an abstract description
of an operation to be performed.

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.
Syntax:
Intent obj_name=new Intent(getApplicationContext(),SecondActivity.class);
startActivity(obj_name);

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.

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);

Using Implicit intent the webpage (google) will directly open

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

Q. Explain Intent filter in android


 In Android, Intent filter is an expression in application manifest file in ActivityMainfest.xml
 Used for type of intents that the component would like to receive.

Syntax of Intent Filter


<intent-filter android:icon="drawable resource"
android:label="string resource"
android:priority="integer" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Sr. Attribute Description


No
1 icon This is displayed as a icon for an activity. Save image of name icon in drawable
folder and used it
2 label The lebel/title that appears at top in Toolbar of that particular activity.We can edit
the name by adding in strings.xml file and used it
3 priority label: priority: The priority use to handling intents of the type described by the
filter.
It provides information about how able an activity is to respond to an intent that
matches the filter, relative to other activities that could also respond to the intent.
When an intent could be handled by multiple activities with different priorities,
Android will consider only those with higher priority values as potential targets
for the intent.

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.

ACTION DATA MEANING


Opens phone application and
Intent.ACTION_CALL tel:phone_number
calls phone number
Opens phone application and
Intent.ACTION_DIAL tel:phone_number dials (but doesn’t call)
phone_number
Opens phone application and
Intent.ACTION_DIAL voicemail: dials (but doesn’t call) the
voice mail number.
Opens the maps Application
Intent.ACTION_VIEW geo:lat,long centered on (latitude,
longtitude).
Opens the maps application
Intent.ACTION_VIEW geo:0,0?q=address centered on the specified
address.
http://url Opens the browser
Intent.ACTION_VIEW https://url application to the specified
address.
Opens the browser
Intent.ACTION_WEB_SEARCH plain_text application and uses Google
search for given string

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.

Activity Life Cycle

Method Description Syntax

onCreate called when activity is first public void onCreate(Bundle SavedinstanceState)


created. {
super.onCreate(savedinstanceState);
}

5
Mobile Application Development 5th Unit P.S.Gaidhani
onStart called when activity is public void onStart()
becoming visible to the user. {
Super.onStart();
}

onResume called when activity will start public void onStart()


interacting with the user. {
super.onStart();
}

onPause called when activity is not public void onPause()


visible to the user. {
super.onPause();
}

onStop called when activity is no public void onStop()


longer visible to the user. {
super.onStop();
}

onRestart called after your activity is public void onRestart()


stopped, prior to start. {
super.onRestart();
}

onDestroy called before the activity is public void onDestroy()


destroyed. {
Super.onDestroy();
}

Ex. Program to show Activity Life Cycle


MainActivity.Java

package com.example.activitylifecycle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

@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

Two Types of Broadcast Intent

 Delivered by System(System Broadcast intents)


 Those that your app delivers(Custom Broadcast intents)

1. System Broadcast Intent


Delivers a system broadcast intent when a system event occurs

Sr.No Event Constant & Description

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.

2. Custom Broadcast Intents


 This intents are those that your application sends out.
 Use a Custom broadcast intent when you want to your app to take an action without
launching an activity

public void broadcastIntent(View view) {


Intent intent = new Intent();
intent.setAction("ggsp.CUSTOM_INTENT");
sendBroadcast(intent);
}

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

1. Creating the Broadcast Receiver


A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the
onReceive() method where each message is received as a Intent object parameter.
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}

2. Registering Broadcast Receiver

An application listens for specific broadcast intents by registering a broadcast receiver


in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event
ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed
the boot process.

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.

A content provider is implemented as a subclass of ContentProvider class and must implement a


standard set of APIs that enable other applications to perform transactions.

public class My Application extends ContentProvider


{

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 −

Sr.No Part & Description

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

public class My Application extends ContentProvider


{

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

 onCreate() This method is called when the provider is started.


 query() This method receives a request from a client. The result is returned as a Cursor object.
 insert()This method inserts a new record into the content provider.
 delete() This method deletes an existing record from the content provider.

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.

Q. Explain Fragments in Android


 A Fragment is a piece of an activity which enable more modular activity design
 Android Fragment is the part of activity, it is also known as sub-activity. There can be more than
one fragment in an activity. Fragments represent multiple screen inside one activity.
 Android fragment lifecycle is affected by activity lifecycle because fragments are included in
activity.
 The FragmentManager class is responsible to make interaction between fragment objects.

Following are important points about fragment


 A fragment has its own layout and its own behaviour with its own life cycle callbacks.
 You can add or remove fragments in an activity while the activity is running.
 You can combine multiple fragments in a single activity to build a multi-pane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of its host activity which means when the
activity is paused, all the fragments available in the activity will also be stopped.
 A fragment can implement a behaviour that has no user interface component.
Following is a typical example of how two UI modules defined by fragments can be combined into one
activity for a tablet design, but separated for a handset design.

14
Mobile Application Development 5th Unit P.S.Gaidhani
Q. Draw & Explain Fragment LifeCycle in Android

No. Method Description

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


activity.

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

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


ViewGroup, Bundle)

15
Mobile Application Development 5th Unit P.S.Gaidhani
4) onActivityCreated(Bundle) It is invoked after the completion of onCreate()
method.

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


saved state of fragment view hierarchy has been
restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

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

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

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

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


state.

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


longer being associated with its activity.

Q. List Types of Fragment


1. Single frame fragments
 Single frame fragment is designed for small screen devices such as hand hold
devices (mobiles) and it should be above android 3.0 version.
2. List fragments
 The basic implementation of list fragment is for creating list of items in fragments

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>

Add two activity activity_fragment1 and activity_fragment2


activity_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".Fragment1Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"
/>
</FrameLayout>

17
Mobile Application Development 5th Unit P.S.Gaidhani
activity_fragment2.xml

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


<FrameLayout 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=".Fragment1Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"
/>
</FrameLayout>

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;

public class Fragment1Activity extends Fragment {

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

public class Fragment2Activity extends Fragment {

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

public class MainActivity extends AppCompatActivity {

@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

Q. Draw & Explain Life Cycle of Android Service

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

1. Started
2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it runs in the
background indefinitely. It is stopped by stopService() 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.

Ex. Program to Implement Service in Android


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

public class MyService extends Service {


MediaPlayer m1;

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

Sr.No Method & description

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

 setAnchorView(View view) – Designates the view to which the controller is to be


anchored. This controls the location of the controls on the screen.
 show() – Displays the controls.
 show(int timeout) – Controls are displayed for the designated duration (in milliseconds).
 hide() – Hides the controller from the user.
 isShowing() – Returns a Boolean value indicating whether the controls are currently

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 setMediaController(MediaController sets the media controller to the video


controller) view.

public void setVideoURI (Uri uri) sets the URI of the video file.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in miliseconds.

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;

public class MainActivity extends AppCompatActivity {


Button b1,b2;
VideoView v1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
v1=findViewById(R.id.v1);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MediaController mediaController=new MediaController(MainActivity.this);
v1.setMediaController(mediaController);
mediaController.setAnchorView(v1);

v1.setVideoURI(Uri.parse("android.resource://" + getPackageName()+ "/" + R.raw.koi));


v1.start();
Toast.makeText(MainActivity.this, "Video Played", Toast.LENGTH_SHORT).show();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
v1.stopPlayback();
Toast.makeText(MainActivity.this, "Video Stopped", Toast.LENGTH_SHORT).show();
}
});
}
}

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 −

private EditText write;


ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()
{
@Override
public void onInit(int status) {
}
});

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 −

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.

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

Android supports three types of sensors:

1) Motion Sensors

These are used to measure acceleration forces and rotational forces along with three axes.

2) Position Sensors

These are used to measure the physical position of device.

3) Environmental Sensors

These are used to measure the environmental changes such as temperature, humidity etc.

Steps to use Sensors:


Step1:
In order to use sensors, first thing you need to do is to instantiate the object of SensorManager class. It
can be achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);

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

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

<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 class MainActivity extends AppCompatActivity {


SensorManager sm = null;
TextView textView1 = null;
List list;
SensorEventListener sel = new SensorEventListener()
{
public void onAccuracyChanged(Sensor sensor, int accuracy)
{

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

/* Get a SensorManager instance */


sm = (SensorManager)getSystemService(SENSOR_SERVICE);

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.

Q. Write a program to capture an image using camera and display it.


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

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

public class MainActivity extends AppCompatActivity {


private static final int CAMERA_REQUEST=1888;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView) this.findViewById(R.id.imageView1);
Button photoButton=(Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent=newIntent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo=(Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}

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.

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

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.

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.

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

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

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

public class MainActivity extends AppCompatActivity {


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);
43
Mobile Application Development 5th Unit P.S.Gaidhani
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);
}
}

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.

In order to perform animation in android,


Step1:
we are going to call a static function loadAnimation() of the class AnimationUtils. We are going to
receive the result in an instance of Animation Object.
Its syntax is as follows −

Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),


R.anim.myanimation);
Note the second parameter. It is the name of the our animation xml file. You have to create a new
folder called anim under res directory and make an xml file under anim folder.
This animation class has many useful functions which are listed below −

Sr.No Method & Description

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 −

ImageView image1 = (ImageView)findViewById(R.id.imageView1);


image.startAnimation(animation);

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;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void clockwise(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
image.startAnimation(animation);
}

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

public void fade(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade);
image.startAnimation(animation1);
}

public void blink(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
image.startAnimation(animation1);
}

public void move(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move);
image.startAnimation(animation1);
}

public void slide(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide);
image.startAnimation(animation1);
}
}

Animation xml Files

Create anim folder and create xml files as below

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

You might also like