0% found this document useful (0 votes)
17 views150 pages

Unit-5_Activity_Mulitmedia with Databases

The document explains the concept of Intents in Android, which are used for communication between app components, including starting activities, services, and delivering broadcasts. It details the types of Intents (explicit and implicit) and how to create and register Broadcast Receivers for handling events. Additionally, it covers the Activity Life Cycle, including its various states and methods, as well as the role of Content Providers in managing access to data.

Uploaded by

Tanuja Jatte
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)
17 views150 pages

Unit-5_Activity_Mulitmedia with Databases

The document explains the concept of Intents in Android, which are used for communication between app components, including starting activities, services, and delivering broadcasts. It details the types of Intents (explicit and implicit) and how to create and register Broadcast Receivers for handling events. Additionally, it covers the Activity Life Cycle, including its various states and methods, as well as the role of Content Providers in managing access to data.

Uploaded by

Tanuja Jatte
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/ 150

Unit 5

Activity, Multimedia with


Databases
Intent
 It is a message passing object, you can use to request an action from another app component.

 The process of taking user from one application to another is achieved by passing the Intent to the
system.

 Intents are used for,

 Navigating among various activities within the same application

 Moving from one application to another application


Intent
 Intents facilitate communication between components in several ways, there are three fundamental
uses cases,

1. Starting an Activity

2. Starting a Service

3. Delivering a broadcast
Intent
1. Starting an Activity

 An Activity represents a single screen in an app.

 You can start a new instance of an Activity by passing an Intent to startActivity().

 The Intent describes the activity to start and carries any necessary data.
Intent
1. Starting an Activity

 Intent : is a messaging object that request an action from another app component.

 MainActivity.this returns the application context.

 SecondActivity.class is the class name of the activity to be launched.

 startActivity(intent): launches an activity.


Intent
2. Starting a Service

 A Service is a component that performs operations in the background without a user interface.

 You can start a Service by passing an Intent to startService().

 The Intent describes Service to start and carries any necessary data.
Intent
3. Delivering a broadcast

 A broadcast is a message that any app can receive.

 The system delivers various broadcasts for system events, such as when the system boots up or the
device starts charging.

 You can deliver broadcast to other apps by passing an Intent to sendBroadcast().


Intent Types
There are two types of Intents,

1. Explicit Intent

2. Implicit Intent
Intent Types
1. Explicit Intent

 When intent specifies which component of which application will satisfy the intent, by specifying
a full ComponentName.

 You will typically use an explicit intent to start a component in you own app, because you know
the class name of the activity or service you want to start.

 For example, you might start a new activity within your app in response to a user action, or start a
service to download a file in background.
Intent Types
1. Explicit Intent

activity_main.xml
Intent Types
1. Explicit Intent

activity_second.xml
Intent Types
1. Explicit Intent

MainActivity.java
Intent Types Creating second activity

1. Expand app directory structure.

2. Expand Java directory and right


click on your package.

3. Select New->Activity->Empty
Views Activity.

4. Opens new Window

5. Name activity as SecondActivity

6. Rest keep default.


SecondActivity.java
Intent Types
2. Implicit Intent

 When intent do not name a specific component, but instead declare a general action to perform,
which allows a component from another app to handle it.

 For example, if you want to show the user a location on a map, you can use an implicit intent to request
that another capable app show a specifies location on map.

 When you use an implicit intent, the Android system finds the appropriate component to start by
comparing contents of the intent to intents filters declared in the Manifest file of other apps on the
device.

 If the intent matches an intent filter, the system starts that component and delivers it the Intent object.

 If multiple filters are compatible, the system displays a dialog so the user can pick up which app to use.
Intent Types
2. Implicit Intent
Intent Types
2. Implicit Intent
Intent Types
2. Implicit Intent

 Action String specifies Action to be performed.

 To specify action usually action constants defined


by Intent Class are used.

 You can specify action for an intent by using


setAction() or by Intent Constructor.
Intent Types
2. Implicit Intent
 Action String specifies Action to be performed.

 To specify action usually action constants defined by Intent Class are used.

 You can specify action for an intent by using setAction() or by Intent Constructor.
Intent Types
2. Implicit Intent

 If multiple filters are compatible,


the system displays a dialog so the
user can pick up which app to use.
Intent Types
2. Implicit Intent

 How an implicit intent is


delivered through the system to
start another activity?

1. Activity A, Creates an Intent with


an action description and passes it to
startActivity().

2. The android system searches 3. When a match found, the system starts
all apps for an intent filter that activity (Activity B) by invoking its onCreate()
matches the intent. method and passing it the Intent.
Intent Filters
 To advertise which implicit intents your app can receive, you need to declare one or more intent
filters for each of your app components with an <intent-filter> element in your manifest file.

 Each intent filter specifies the type of intents it accepts based on the intent’s action, data and
category.

 The system delivers an implicit intent to your app component only if the intent can pass
through one of your intent filter.

 The app component should declare separate filters for each unique job it can do.

For example, one activity in an image gallery app may have two filters: one filter to view an image,
and another filter to edit an image. When activity starts, it inspects the Intent and decides how to
behave based on the information in the Intent.
Intent Filters
 Inside the <intent-filter>, you can specify the type of intents to accept using one or more of
these three elements.

1. <action>

Declares the intent action accepted, in the name attribute. The value must be the literal string value
of an action.
Intent Filters
2. <data>

Declares the type of data accepted, using one or more attributes that specify various aspects of the data
URI(scheme, host, port, path) and MIME type.

<scheme>://<host>:<port>[path]
Intent Filters
2. <data>

Android:mimeType=“”

 It is a media type or content type and used to identify the format of a file or content.

 It is used to indicate how a file should be processed and displayed.


Intent Filters
3. <category>

 Declares the intent category accepted, in the name attribute. The value must be the literal string
value of an action.

 It provides additional information about the kind of action or interaction the component is designed
to support.

<category android:name="android.intent.category.LAUNCHER" />

 This is used to indicate that component is a main entry point for the application.

<category android:name="android.intent.category.BROWSABLE"/>

 This category allows the component to be invoked from a browser.

<category android:name="android.intent.category.DEFAULT"/>
 This is the default category, if you don’t explicitly specify a category.
Intent Filters
For Example, here is activity declaration with an intent filter to receive an ACTION_SEND intent when
the data type is text.
Activity Life Cycle

 The life cycle of an Android application is strictly managed by the system, based on the user’s
needs, available resources, and so on.

 A user may want to launch a web browser, for example, but the system ultimately decides whether
to start the application.

 Although the system is the ultimate manager, it adheres to some defined and logical guidelines to
determine whether an application can be loaded, paused, or stopped.

 If the user is currently working with an activity, the system gives high priority to that application.

 Conversely, if an activity is not visible and the system determines that an application must be shut
down to free up resources, it shuts down the lower-priority application.
Activity Life Cycle

 The processes running your Android application and its components go through various life-cycle
events, and Android provides callbacks that you can implement to handle state changes.

 Life-Cycle Methods of an Activity

protected void onCreate(Bundle savedInstanceState);


protected void onStart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onRestart();
protected void onDestroy();
Activity Life Cycle
Figure shows the transitions between states.
Activity Life Cycle
onCreate()

 This method is executed when the activity is being created.

 Here, we get everything ready for the app, including the UI (such as calling setContentView), graphics,
and sound etc.

onStart()

 This method is executed when the app is in the starting phase.

 This method pushes the activity into a visible state. In other words this method starts visible
lifecycle of the activity.

 This method can also be called when the activity is shown after being hidden first, because another
activity has come to the top of the visibility stack.

 Called after the onRestart(), which itself is triggered after the onStop().
Activity Life Cycle
onResume()

 onResume() to having the activity fully visible. This is also start of Foreground lifecycle.

 In foreground lifecycle the activity can move between onResume() and onPause() multiple times as
other activities, notifications, dialogs with more urgency come on top and go.

 This method runs after onStart() but can also be entered (most logically) after our activity is resumed
after being previously paused.

 We might reload previously saved user data (such as an important note) from when the app was
interrupted, perhaps by a phone call or the user running another app.
Activity Life Cycle
onPause()

 This occurs when our activity is pausing and is about to go into background.

 Here, we might save unsaved data (such as the note) that could be reloaded in onResume().

 Activities always transition into a paused state when another UI element is displayed on top of the
current activity (for example, a pop-up dialog)

 When the activity is about to be stopped (for example, when the user navigates to a different activity).
Activity Life Cycle
onStop()

 This relates to the stopping phase. It moves the activity from partially visible to the background state
while keeping all of the view hierarchy intact.

 This activity can be taken back to the visible cycle by calling onStart().

 This is where we might undo everything we did in onCreate, such as releasing system resources or
writing information to a database.

 If we reach here, we are probably going to get destroyed sometime soon.


Activity Life Cycle
onRestart()

 This method is called when the activity transitions from background state to partially visible state , i.e.
going from onStop() to onStart();

onDestroy()

 This is when our activity is finally being destroyed.

 There is no turning back from this phase.

 If we reach here, we will be going through the lifecycle phases from the beginning next time.

 It can be called explicitly by user, activity can close involuntary, by system when it needs memory.
Activity Life Cycle Example
@Override
protected void onPause()
public class MainActivity extends AppCompatActivity { {
super.onPause();
@Override Toast.makeText(this,"onPause", Toast.LENGTH_LONG).show();
protected void onCreate(Bundle savedInstanceState) { }
super.onCreate(savedInstanceState); @Override
setContentView(R.layout.activity_main); protected void onStop()
Toast.makeText(this,"onCreate", Toast.LENGTH_LONG).show(); {
super.onStop();
} Toast.makeText(this,"onStop", Toast.LENGTH_LONG).show();
@Override }
protected void onStart() @Override
{ protected void onRestart()
super.onStart(); {
Toast.makeText(this,"onStart", Toast.LENGTH_LONG).show(); super.onRestart();
} Toast.makeText(this,"onRestart", Toast.LENGTH_LONG).show();
@Override }
protected void onResume() @Override
{ protected void onDestroy()
super.onResume(); {
Toast.makeText(this,"onResume", Toast.LENGTH_LONG).show(); super.onDestroy();
} Toast.makeText(this,"onDestroy", Toast.LENGTH_LONG).show();
}
}

MainActivity.java
Broadcast Life Cycle
Broadcast Receiver

 Broadcast receivers simply respond to broadcast messages from other applications or from the
system itself.

 These messages are sometimes called events or intents.

 For example, application can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and available for them to use.

 These kind broadcast can be sent for various events like when the device is charging, wi-fi is connected,
screen is turned off, device booted etc.

 So the broadcast receiver who will intercept this communication and will initiate the appropriate action.
Broadcast Life Cycle
There are two important steps to make broadcast receiver that works for the system,

1. Creating Broadcast Receiver

2. Registering the Broadcast Receiver


Broadcast Life Cycle
1. Creating Broadcast Receiver

 A Broadcast Receiver is implemented as a subclass of BroadcastReceiver class and overriding the


onReceiver() method.

 Where each message is received as a intent object parameter.

 The onReceive() method contains action to be performed when the broadcast is received.
1. Creating Broadcast Receiver for handling Power Source Connected /Disconnected

PowerReceiver.java
Broadcast Life Cycle
2. Registering the Broadcast Receiver

Static Registration

 An application listens for specific broadcast intents by registering as a broadcast receiver in


AndroidManifest.xml file.

 This method registers the receiver to listen for specific system-wide broadcasts even when your
app is not running.

 This registration happen in AndroidManifest.xml file.


Broadcast Life Cycle
2. Registering the Broadcast Receiver

Dynamic Registration (In Java Code)

 If you want to register the receiver at runtime, use the registerReceiver() method.

 This method requires a BroadcastReceiver instance and an IntentFilter to specify the type of
broadcast you want to listen for.
Dynamic Registration (In Java Code)
Broadcast Life Cycle
Broadcasting an Intent

 To send a broadcast, you can use the sendBroadcast() method.

 It can be used to send a global broadcast or local broadcasts.

 Example of sending a simple broadcast,

Intent intent=new Intent(“com.example.MY_CUSTIOM_BROADCAST”);


sendBroadcast(intent);

 You can create such custom actions like above and listen for them in your receiver.
Broadcast Life Cycle

Gets Notification when


intent/intents Occur.

Android Broadcast
System Receiver

Register for intents to


observe.

Fig. Broadcast Lifecycle


Broadcast Life Cycle

Broadcast Receiver, receives messages (events or intents) generated by system or other application to
which it was registered.
Broadcast Life Cycle
System Level Broadcasts

 These broadcasts are sent by system to notify apps about various events or system changes.

Broadcast Action Description


BOOT_COMPLETED android.intent.action.BOOT_COMPLETED Sent when device has finished
booting.
ACTION_POWER_CONN android.intent.action. Sent when device is connected
ECTED ACTION_POWER_CONNECTED to power source
ACTION_POWER_DISC android.intent.action. Sent when device is
ONNECTED ACTION_POWER_DISCONNECTED disconnected the power source

ACTION_AIRPLANE_MO android.intent.action.AIRPLANE_MODE Sent when the airplane mode is


DE_CHANGED toggled.
Broadcast Life Cycle
System Level Broadcasts

 These broadcasts are sent by system to notify apps about various events or system changes.

Broadcast Action Description


ACTION_BATTERY_LOW android.intent.action.BATTERY_LOW Sent when device’s battery is low.
WIFI_STATE_CHANGED android.intent.action.WIFI_STATE_CHAN Sent when wi-fi state
GED changes(connected,disconnected)
ACTION_SCREEN_ON android.intent.action.SCREEN_ON Sent when screen is turned ON
ACTION_SCREEN_OFF android.intent.action.SCREEN_OFF Sent when screen is turned OFF

SMS_RECEIVED android.provider.Telephony.SMS_RECEIV Sent when a new sms messages is


ED received.
Content Provider
 A content provider manages access to a central repository of data.

 It facilitate other applications to securely access and modifies that data based on the user requirement.

Some of the functionalities by content


provider

 Sharing access to your application data with


other applications.

 Returning custom search suggestions for your


application

 Synchronizing app data with your server

 Loading data in your UI using Cursor Loader.


Content Provider
Access a Provider

 When we want to access data in a content


provider, we use ContentResolver object in
our application context to communicate with
ContentProvider.

 The ContentProvider object receives data


requests from clients, performs the requested
action, and returns the result.

 The ContentResolver methods provide the


basic “CRUD” (Create, Read/Retrieve,
Update, Delete) functions of storage.
Content Provider

 There are six abstract methods which are essential to override as the a part of Content Provider.

Abstract Method Description


query() Fetches data from the desired table.
insert() To insert a new row in the database of the content provider.
update() This method is used to update the fields of an existing row.
delete() This method is used to delete the existing row.
onCreate() As the content provider is created and initialized
Services
 A Service is an application component that can perform long running operations in the background.

 It does not provide user interface.

 Once started, a service might continue running for some time, even after the user switches to another
application.

For example,

 Service can handle network transaction, play music, perform file I/O, or interact with content provider etc.
Features of Services

1. Background Task Execution.


 Services allow apps to run long term operations without blocking the user interface.

2. Runs independently
 Runs on its own thread, independent of main UI thread.

3. Life Span
 Services can run indefinitely, even when the application is not in the foreground, until explicitly stopped.

4. Inter application communication


 Services can be used to communicate between different applications or components.

5. Support for multiple clients.


 Services allow multiple components to bind to it, providing access shared resource and services.
Service Lifecycle

 A service is a component that runs in the background to perform long-running operations


without needing to interact with the user and it works even if application is destroyed.

 A service can essentially take two states

Sr.No. State & Description


Started
A service is started when an application component, such as an activity, starts it by
1 calling startService(). Once started, a service can run in the background
indefinitely, even if the component that started it is destroyed.

Bound
A service is bound when an application component binds to it by
2 calling bindService(). A bound service offers a client-server interface that allows
components to interact with the service, send requests, get results, and even do so
across processes with interprocess communication (IPC).
Service Lifecycle

 A service has life cycle callback


methods that we can implement to
monitor changes in the service’s
state.

 We can perform work at the


appropriate stage.

 The following diagram on the left


shows the life cycle when the
service is created with
startService()

 The diagram on the right shows the


life cycle when the service is created
with bindService()
Service Lifecycle

 To create a service, you create a Java class that extends the Service base class or one of its existing
subclasses.

 The Service base class defines various callback methods and the most important are given below.

 You don't need to implement all the callbacks methods. However, it's important that you understand each
one and implement those that ensure your app behaves the way users expect.
Service Lifecycle
Sr.No. Callback & Description
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
1
responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.

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

onUnbind()
3 The system calls this method when all clients have disconnected from a particular
interface published by the service.
Service Lifecycle

Sr.No. Callback & Description


onRebind()
The system calls this method when new clients have connected to the service, after it had
4
previously been notified that all had disconnected in its onUnbind(Intent).

onCreate()
The system calls this method when the service is first created
5 using onStartCommand() or onBind(). This call is required to perform one-time set-
up.

onDestroy()
The system calls this method when the service is no longer used and is being
6 destroyed. Your service should implement this to clean up any resources such as
threads, registered listeners, receivers, etc.
Example of Service
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Example of Service"
android:gravity="center"
android:textSize="30sp"/>
<Button
android:id="@+id/startService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:textSize="25sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>

<Button
android:id="@+id/stopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:textSize="25sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>

</LinearLayout> activity_main.xml
public class ExampleService extends Service {
@Override
public void onCreate(){
super.onCreate();
//Initialize Resource
}
@Override
public int onStartCommand(Intent intent,int flag, int startId)
{
//do background task here
Toast.makeText(getApplicationContext(),"Service Started",Toast.LENGTH_LONG).show();
return START_STICKY; //restart the service, if it is get killed.
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
public void onDestroy()
{
//release resources
super.onDestroy();
Toast.makeText(getApplicationContext(),"Service Stopped",Toast.LENGTH_LONG).show();
}

} ExampleService.java
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button btnStart=(Button)findViewById(R.id.startService);
Button btnStop=(Button)findViewById(R.id.stopService);

btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,ExampleService.class);
startService(intent);
}
});

btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,ExampleService.class);
stopService(intent);
}
});
}
}
MainActivity.java
<application>
<service android:name=".ExampleService"/>
</application>
AndroidManifest.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ringtone Service"
android:gravity="center"
android:textSize="30sp"/>

<Button
android:id="@+id/startService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:textSize="25sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>

<Button
android:id="@+id/stopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:textSize="25sp" activity_main.xml
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>
public class RingtoneService extends Service {
private Ringtone ringtone;
@Override
public void onCreate(){
super.onCreate();
Uri ringtoneUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
ringtone=RingtoneManager.getRingtone(getApplicationContext(),ringtoneUri);
}
@Override
public int onStartCommand(Intent intent,int flag, int startId)
{
if(ringtone!=null && !ringtone.isPlaying())
{
ringtone.play();

}
return START_STICKY; //restart the service, if it is get killed.
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
public void onDestroy()
{
//release resources
super.onDestroy();
if(ringtone!=null && ringtone.isPlaying())
{
ringtone.stop();
}
}
}

RingtoneService.java
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart=(Button)findViewById(R.id.startService); <service android:name=".RingtoneService"/>
Button btnStop=(Button)findViewById(R.id.stopService); </application>

btnStart.setOnClickListener(new View.OnClickListener() { AndroidManifest.xml


@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,RingtoneService.class);
startService(intent);
}
});

btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,RingtoneService.class);
stopService(intent);
}
});
}
}
MainActivity.java
Multimedia Framework
 The android multimedia system includes multimedia applications, multimedia frameworks,
OpenCore engine and hardware for audio/video input/output devices.

 The goal of the android multimedia framework is to provide a reliable interface for java services.

 The multimedia framework consists of several core dynamic libraries such as libmediajni,
libmedia, libmediaplayservice.
Multimedia Framework

 Java classes call the Native C library Libmedia


through Java JNI(Java Native Interface).

 Libmedia library communications with Media


Server.

 Media Server process creates the corresponding


multimedia service according to the Java
multimedia applications.
Multimedia Framework
libmedia

 It refers to the core library (written in C / C++) responsible for fundamental media functionalities like
playback and recording.

media_jni

 It act as bridge between the Java Media framework and the native libmedia library, allowing java
code to interact with media operations through JNI.

Media server
 A system level process responsible for managing media decoding, playback, streaming.
 Provides access various codecs to handle different file formats.

Media Player
 A java class within the android SDK that used to control media playback in apps.
 Offers functionalities like play, pause, stop, seek and manage playback events.
 Can play both video and audio files from the local storage as well as network stream.
Multimedia Framework
How does it work?

 When Java application in Android wants to perform a media operation(like playing a video/audio), it calls to
a method in Java Media framework.

 This Java method then invokes a native function within the “media_jni” layer.

 “media_jni” then communicates with the appropriate functions in libmedia to execute the media
operation on the native level.

 Then PVPlayer processes the media data stream with the steps:

1. demux the media data to separate video/audio data stream


2. decode video/audio data
3. sync video, audio time, send the decoded data out.
Play Audio and Video

The following classes play audio and video in Android framework,

1. MediaPalyer : This class is the primary API for playing audio and video.

2. AudioManager: This class manages audio sources and audio output on a device. It mostly
support volume and ringer related services.
Play Audio and Video

 Using the Media APIs Android supports playing audio and video content under the android.media
package.

 At the heart of the android.media package is the android.media.MediaPlayer class.

 The MediaPlayer class is responsible for playing both audio and video content.

 The content for this class can come from the following sources:

 Web: You can play content from the Web via a URL.
 .apk file: You can play content that is packaged as part of your .apk file.
 The Storage Access Framework, which provides access to media files stored across a range of
providers and internet services.
 SD card: You can play content that resides on the device’s SD card or emulated local storage.
Play <TextView <Button
android:layout_width="match_parent" android:id="@+id/pause"
Audio android:layout_height="wrap_content" android:layout_width="200dp"
android:text="Audio Player" android:layout_height="wrap_content"
android:textSize="40sp" android:text="Pause"
android:textStyle="bold" android:textSize="35sp"
android:gravity="center"/> android:layout_gravity="center"/>

<Button </LinearLayout>
android:id="@+id/play"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Play"
android:textSize="35sp"
android:layout_gravity="center"/>

<Button
android:id="@+id/stop"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Stop"
android:textSize="35sp"
android:layout_gravity="center"/>
activity_main.xml
Play Audio

public class MainActivity extends AppCompatActivity {


@Override stop.setOnClickListener(new View.OnClickListener() {
protected void onCreate(Bundle savedInstanceState) { @Override
super.onCreate(savedInstanceState); public void onClick(View v) {
setContentView(R.layout.activity_main); mediaPlayer.stop();
}
Button play=(Button) findViewById(R.id.play); });
Button stop=(Button) findViewById(R.id.stop); pause.setOnClickListener(new View.OnClickListener() {
Button pause=(Button) findViewById(R.id.pause); @Override
public void onClick(View view) {
MediaPlayer mediaPlayer= mediaPlayer.pause();
MediaPlayer.create(getApplicationContext(),R.raw.sound_file_1); }
});
play.setOnClickListener(new View.OnClickListener() { }
@Override }
public void onClick(View v) {

mediaPlayer.start();
}
});
MainActivity.java
Play Video
<TextView
<Button
android:layout_width="match_parent"
android:id="@+id/pause"
android:layout_height="wrap_content"
android:layout_width="150dp"
android:text="Media Player"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Pause"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"/>
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
<VideoView
android:layout_height="wrap_content"
android:id="@+id/video"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_gravity="center">
android:layout_height="600dp"/>
<Button
</LinearLayout>
android:id="@+id/play"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Play"
android:textSize="20sp" activity_main.xml
android:layout_gravity="center"
android:layout_marginRight="20dp"/>
public class MainActivity extends AppCompatActivity { Play Video
@Override
protected void onCreate(Bundle savedInstanceState) { play.setOnClickListener(new View.OnClickListener() {
super.onCreate(savedInstanceState); @Override
setContentView(R.layout.activity_main); public void onClick(View view) {
Button play=(Button) findViewById(R.id.play);
Button pause=(Button)findViewById(R.id.pause) ; videoView.start();
VideoView videoView=(VideoView) findViewById(R.id.video); Toast.makeText(getApplicationContext(),
"Playing",Toast.LENGTH_LONG).show();
String videoPath="android.resource://"+getPackageName()+ }
"/"+(R.raw.sample_video); });
Uri videoUri= Uri.parse(videoPath); pause.setOnClickListener(new View.OnClickListener() {
videoView.setVideoURI(videoUri); @Override
public void onClick(View view) {
videoView.pause();
Toast.makeText(getApplicationContext(),
"Paused",Toast.LENGTH_LONG).show();
}
});

}
}
MainActivity.java
Play Video
Text To Speech

 TextToSpeech android feature synthesizes speech from text for immediate playback or to
create a sound file.

 In android, by using TextToSpeech class we can easily convert our text into voice and it
supports different types of speaking languages.

 We can choose the speaking language based on our requirements in the android
application.

 The android TextToSpeech instance can only be used to synthesize text once it has
completed its initialization so implement TextToSpeech.

 OnInitListener to notify the completion of initialization. During the initialization, we can set the
audio pitch rate, audio speed, type of language to speak, etc. based on our requirements.
Text To Speech
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text To Speech"
android:textSize="25sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="20dp"/>
<EditText
android:id="@+id/etspeak"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="Type to Listen"
android:textSize="25sp"
android:layout_marginBottom="20dp"/>
<Button
activity_main.xml android:id="@+id/speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Speak"
android:textSize="25dp"
android:layout_gravity="center"/>

</LinearLayout>
public class MainActivity extends AppCompatActivity { Text To Speech
Button speakButton; speakButton.setOnClickListener(new View.OnClickListener() {
EditText etSpeak; @Override
TextToSpeech tts; public void onClick(View v) {
@Override tts.speak(etSpeak.getText().toString(),TextToSpeech.QUEUE_FLUSH,
protected void onCreate(Bundle savedInstanceState) { null);
super.onCreate(savedInstanceState); }
setContentView(R.layout.activity_main); });
}
speakButton=(Button) findViewById(R.id.speak); }
etSpeak=(EditText) findViewById(R.id.etspeak); MainActivity.java

tts=new TextToSpeech(this, new TextToSpeech.OnInitListener() {


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

}
});
Text To Speech
Sensors
 Most Android-powered devices have built-in sensors that measure motion, orientation, and various
environmental conditions.

 These sensors are capable of providing raw data with high precision and accuracy.

 These are useful, if you want to monitor three-dimensional device movement or positioning, or
you want to monitor changes in the ambient environment near a device.

For example,
A game might track readings from a device's gravity sensor to infer complex user
gestures and motions, such as tilt, shake, rotation, or swing.
Sensors
 The Android platform supports three broad categories of sensors:

 Motion sensors
These sensors measure acceleration forces and rotational forces along three axes. This category
includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.

 Environmental sensors
These sensors measure various environmental parameters, such as ambient air temperature and
pressure, illumination, and humidity. This category includes barometers, photometers, and
thermometers.

 Position sensors
These sensors measure the physical position of a device. This category includes orientation
sensors and magnetometers.
Sensors
The Android sensor framework lets you access many types of sensors. Some of these sensors are hardware-
based and some are software-based.
Sensors
Sensors
Sensors
Ex. Android Application to display list of available sensors on a device.

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List of Sensors"
android:textSize="25sp"
android:textStyle="bold"
android:gravity="center"/>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</LinearLayout>
activity_main.xml
Sensors
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView) findViewById(R.id.listView);

SensorManager sm=(SensorManager)getSystemService(SENSOR_SERVICE);

List <Sensor>sensorList=sm.getSensorList(Sensor.TYPE_ALL);

List<String> sensorNames=new ArrayList<String>();


for(Sensor sensor:sensorList)
{
sensorNames.add(sensor.getName());
}

ArrayAdapter<String> adapter=new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1,sensorNames);
listView.setAdapter(adapter);
}
}
MainActivity.java
Sensors
Ex. Android Program to change background color on device shuffle.

 First thing is you have instantiate the object of class SensorManager as,

SensorManager sm=(SensorManager)getSysteService(SENSOR_SERVICE);

 Next is to instantiate object of class Sensor as by calling method getDefaultSensor() of Class


SensorManager.

Sensor accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensors
Ex. Android Program to change background color on device shuffle.
 Once sensor declaration is over, you need register the sensor listener and override two methods
as follows,

Registering Sensor:
sm.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
sm.registerListener(SensorListener listener, Sensor sensor, int rate);

@Override:

public void onSensorChanged(SensorEvent event){

\\ write here what to do on change of sensor data


}

public void onAccuracyChanged(Sensor sensor,int accuracy){


\\ write here what to do on change of accuracy.
}
Sensors
Ex. Android Program to change background color on device shuffle.

 Finally, we unregister the registered sensor during onPause() / onStop(), in order release the sources
and save battery life.

Un-registering Sensor:

public void onPause()


{

super.onPause();
unregisterListener( SensorListener listener, Sensor sensor);

}
Ex. Android Program to change background color on device shuffle.
public class MainActivity extends AppCompatActivity implements SensorEventListener {
SensorManager sm;
Sensor accelerometer;
float lastX,lastY,lastZ;
View view;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.tv);
view=(View)findViewById(R.id.main);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

@Override
public void onResume()
{
super.onResume();
sm.registerListener(this,accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event)
{

if(event.sensor.getType()!=Sensor.TYPE_ACCELEROMETER)
{
return;
}

float x=event.values[0];
@Override float y=event.values[1];
public void onPause() float z=event.values[2];
{ String values="X:"+x+"\n"+"Y:"+y+"\n"+"Z:"+z;
super.onPause(); tv.setText(values);
sm.unregisterListener(this);
} float movement=Math.abs(x+y+z-lastX-lastY-lastZ);

if(movement>10)
{
changeColor();
}

lastX=x;
lastY=y;
lastZ=z;
}
public void changeColor()
{

view.setBackgroundColor(Color.parseColor("#FF8DA1”));
}

@Override
public void onAccuracyChanged(Sensor sensor, int
accuracy)
{

}
}
Camera
 The Android framework includes support for various cameras and camera features available on
devices, allowing you to capture pictures and videos in your applications.

 The Android framework supports capturing images and video through android.hardware.camera2 API
or camera Intent.
Camera
Here are the relevant classes:
android.hardware.camera2

 This package is the primary API for controlling device cameras. It can be used to take pictures or
videos when you are building a camera application.

Camera
This class is the older deprecated API for controlling device cameras.

SurfaceView
This class is used to present a live camera preview to the user.

MediaRecorder
This class is used to record video from the camera.

Intent

MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_VIDEO_CAPTURE can be used to


capture images or videos without directly using the Camera object.
Manifest declarations
Before starting development on your application with the Camera API, you should make sure your
manifest has the appropriate declarations to allow use of camera hardware and other related
features.

• Camera Permission - Your application must request permission to use a device camera.

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

• Camera Features - Your application must also declare use of camera features, for example

<uses-feature android:name="android.hardware.camera" />

• Storage Permission - Your application can save images or videos to the device's external storage (SD
Card) if it targets Android 10 (API level 29) or lower and specifies the following in the manifest.

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


Manifest declarations
• Audio Recording Permission - For recording audio with video capture, your application must request
the audio capture permission.

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

• Location Permission - If your application tags images with GPS location information, you must request
the ACCESS_FINE_LOCATION permission.

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


Building a camera app

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Camera Application"
android:gravity="center"
android:textSize="25sp"
android:textStyle="bold"/>
<ImageView
android:id="@+id/imgview"
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginBottom="15dp"/>
<Button
android:id="@+id/camOpen"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center|bottom"
android:text="Open_Camera"
android:textSize="20sp"/>

</LinearLayout>
activity_main.xml
Building a camera app

public class MainActivity extends AppCompatActivity {


ImageView imgView;
Button openCamera;
int CAMERA_REQUEST=100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView=(ImageView)findViewById(R.id.imgview);
openCamera=(Button)findViewById(R.id.camOpen);

//Requesting camera permission at runtime


if(ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST);
}
MainActivity.java
Building a camera app
//Open Camera when button is clicked
openCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
});
}

//Handle Captured Image


@Override
public void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==CAMERA_REQUEST&&resultCode==RESULT_OK) {
Bitmap bitimage=(Bitmap)data.getExtras().get("data");
imgView.setImageBitmap(bitimage);
}
else {
Toast.makeText(getApplicationContext(),
"Camera Image Capture Failed",Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
Building a camera app

AndroidManifest.xml

<uses-feature android:name="android.hardware.camera" android:required="true"/>

<uses-permission android:name="android.permission.CAMERA"/>
Recording Video

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Camera Application"
android:gravity="center"
android:textSize="25sp"
android:textStyle="bold"/>

<VideoView
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginBottom="15dp"/>

<Button
android:id="@+id/camOpen"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center|bottom"
android:text="Record/Play Video"
android:textSize="20sp"/>
</LinearLayout>
activity_main.xml
Recording Video

public class MainActivity extends AppCompatActivity {

VideoView videoView;
Button openCamera;
int CAMERA_REQUEST=100;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView=(VideoView)findViewById(R.id.videoview);
openCamera=(Button)findViewById(R.id.camOpen);

//Requesting camera permission at runtime


if(ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST);
}
Recording Video
//Open Camera when button is clicked
openCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent= new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
});
}

//Handle Captured Image


@Override
public void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==CAMERA_REQUEST&&resultCode==RESULT_OK) {
Uri videoUri=data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
else {
Toast.makeText(getApplicationContext(),
"Camera Video Capture Failed",Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
Recording Video

AndroidManifest.xml

<uses-feature android:name="android.hardware.camera" android:required="true"/>


<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
luetooth
 The Android platform includes support for the Bluetooth network stack, which allows a device to
wirelessly exchange data with other Bluetooth devices.

 The app framework provides access to the Bluetooth functionality through Bluetooth APIs.

 These APIs let apps connect to other Bluetooth devices, enabling point-to-point and multipoint
wireless features.
luetooth
Using the Bluetooth APIs, an app can perform the following:

 Scan for other Bluetooth devices.


 Query the local Bluetooth adapter for paired Bluetooth devices.
 Connect to other devices through service discovery.
 Transfer data to and from other devices.
 Manage multiple connections.
luetooth

 For Bluetooth-enabled devices to transmit data between each other, they must first form a channel of
communication using a pairing process.

 One device, a discoverable device, makes itself available for incoming connection requests. Another
device finds the discoverable device using a service discovery process.

 After the discoverable device accepts the pairing request, the two devices complete a bonding process
in which they exchange security keys.

 After the pairing and bonding processes are complete, the two devices exchange information.
Ex. Android Program to Turn ON, Turn OFF, List available devices,
luetooth get visible/discoverable.

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Demo" <Button
android:textSize="25sp" android:layout_width="match_parent"
android:textStyle="bold" android:layout_height="wrap_content"
android:gravity="center"/> android:text="Discover"
android:textSize="20sp"
<Button android:id="@+id/discover"
android:layout_width="match_parent" android:gravity="center"/>
android:layout_height="wrap_content"
android:text="Turn ON" <Button
android:textSize="20sp" android:layout_width="match_parent"
android:id="@+id/turnOn" android:layout_height="wrap_content"
android:gravity="center"/> android:text="List"
android:textSize="20sp"
<Button android:id="@+id/list"
android:layout_width="match_parent" android:gravity="center"/>
android:layout_height="wrap_content"
android:text="Turn OFF" </LinearLayout>
android:textSize="20sp"
android:id="@+id/turnOff"
android:gravity="center"/>
public class MainActivity extends AppCompatActivity {

Button buttonTurnOn, buttonTurnOff,buttonDiscover, buttonList;


BluetoothAdapter bAdapter;
int BluetoothRequest=1;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

buttonTurnOn=findViewById(R.id.turnOn);
buttonTurnOff=findViewById(R.id.turnOff);
buttonDiscover=findViewById(R.id.discover);
buttonList=findViewById(R.id.list);
lv=findViewById(R.id.lv);

bAdapter=BluetoothAdapter.getDefaultAdapter();
buttonTurnOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

/*if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT},BluetoothRequest);
}*/

//above code needed when android version is greater than 11(android 12+).

if(bAdapter==null)
{
Toast.makeText(MainActivity.this,
"Bluetooth Not Supported by Device",Toast.LENGTH_LONG).show();
}
else if(!bAdapter.isEnabled())
{
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
Toast.makeText(MainActivity.this,
"Bluetooth Turning ON",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,
"Already Turned ON",Toast.LENGTH_LONG).show();
}
}
});
buttonTurnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if(bAdapter!=null&&bAdapter.isEnabled())
{
/*Intent intent=new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intent);*/
//above code needed when android version is greater than 11(android 12+).

bAdapter.disable(); //comment this when you use Android 12+

Toast.makeText(MainActivity.this,
"Turning OFF",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,
"Already Turned OFF",Toast.LENGTH_LONG).show();
}
}
});
buttonDiscover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

/*if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT},BluetoothRequest);
}*/
//above code needed when android version is greater than 11.
Intent intentDiscoverable=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(intentDiscoverable);
Toast.makeText(MainActivity.this,
"Device is now Discoverable",Toast.LENGTH_LONG).show();
}
});
buttonList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

/*if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT},BluetoothRequest);
}*/
//above code need when android version is greater than 11.
Set<BluetoothDevice> deviceList=bAdapter.getBondedDevices();
List<String>deviceNames=new ArrayList<String>();
for(BluetoothDevice device:deviceList)
{
deviceNames.add(device.getName());
}
ArrayAdapter<String>adapter=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_expandable_list_item_1,deviceNames);
lv.setAdapter(adapter);
}
});
AndroidManifest.xml

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-feature android:name="android.hardware.bluetooth"/>
Animation
 Animation is process of adding motion, effects to any view, image or text.

 The normal way to create an animation in Android is through XML.

 We can write XML animations and then load and play them in Java, on a specific UI widget.
Animation
Fade IN and OUT

Alpha is a measure of transparency, by stating the starting fromAlpha and ending toAlpha values, we
can fade items in and out.

A value 0.0 is invisible and 1.0 is an object’s normal appearance. Steadily moving between the two
makes a fading effect.
Fade IN
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Animation Demo"
android:textSize="25sp"
android:textStyle="bold"
android:gravity="center"
/>
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/logo"
/>

<Button
android:id="@+id/fadeIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade In "
android:textSize="25sp"/>
</LinearLayout>
Activity_main.xml
Fade IN
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0.0"
android:duration="8000"
android:toAlpha="1.0"/>
</set>
fadein.xml

 Create a new Android Resource Directory as: “anim”


under res (Resource) directory.

 Create a new Animation Resource File as: “fadein” and


root element as “set”
Fade IN
public class MainActivity extends AppCompatActivity {

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

ImageView img=(ImageView) findViewById(R.id.img);


Button btnFadeIn=(Button)findViewById(R.id.fadeIn);

//Declare an animation object.


Animation animFadeIn;

//Initialize it
animFadeIn= AnimationUtils.loadAnimation(this,R.anim.fadein);

btnFadeIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
img.startAnimation(animFadeIn);
}
});
}
}
Fade OUT

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


<set
xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="1.0"
android:duration="8000"
android:toAlpha="0.0"/>
</set>
fadeout.xml
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img=(ImageView) findViewById(R.id.img);
Button btnFadeIn=(Button)findViewById(R.id.fadeIn);
Button btnFadeOut=(Button)findViewById(R.id.fadeOut);
//Declare an animation object.
Animation animFadeIn, animFadeOut;
//Initialize it
animFadeIn= AnimationUtils.loadAnimation(this,R.anim.fadein);
animFadeOut= AnimationUtils.loadAnimation(this,R.anim.fadeout);

btnFadeIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
img.startAnimation(animFadeIn);
}
});
btnFadeOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnFadeOut.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animFadeOut);
}
});
}} Fade OUT
Animation
Zoom IN and OUT

 By using Scale value we can control its X direction and Y direction scaling.

 If we increase both the values uniformly then it appears to be Zoomed IN and if decreased uniformly it
appears to be Zoomed OUT.

 So, starting fromXScale and ending toXScale values creates Zoom animation effect.

 The pivotX and pivotY defines the pivot point against which we are going to zoom.
Zoom In

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:duration="8000"
android:toXScale="6"
android:toYScale="6"
/>
</set>
zoomin.xml
Zoom In

btnZoomIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnZoomIn.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animZoomIn);
}
});
Zoom Out
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="6"
android:fromYScale="6"
android:pivotX="50%"
android:pivotY="50%"
android:duration="8000"
android:toXScale="1"
android:toYScale="1"
/>
</set>
zoomout.xml

btnZoomout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnZoomout.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animZoomOut);
}
});
Animation
Rotate Clockwise & Anti-Clockwise

 By using rotate element of XML we can control the rotation of a view in clockwise or anti clockwise
direction.

 The starting fromDegree and ending toDegree help us to rotate the view.

For entire MainActivity.java content:


https://drive.google.com/file/d/1MLzlPkQHHFZFn0M16Q4aaljBn9X0yMrR/view?usp=sharing
Rotate Clockwise

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="8000"
android:toDegrees="360"/>
</set>
rotateclk.xml

btnRotateClk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnRotateClk.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animRotateClk);
}
});
Rotate Anti Clockwise

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="8000"
android:toDegrees="0"/>
</set>
rotateanticlk.xml

btnRotateAntiClk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnRotateAntiClk.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animRotateAntiClk);
}
});
SQLite Database
 SQLite is a data storage available in Android where we can store data in user’s device and can use it
any time when required.

 SQLite database allows us to perform basic CRUD(Create, Read/Retrieve, Update, Delete)


operations in Android.
SQLite API

 The SQLiteDatabase class is the class that represents the actual database.

 The SQLiteOpenHelper class is where most of the action take place.

 It is a helper class for managing SQLite database creation, version management, and database
upgrades.

 The subclasses which extends it , are required to override two methods of it onCrearte() and
onUpgrade();

 onCreate(): This method is called when the database is created for the first time, allowing you to
create tables and define database schema.

 onUpgrade(): This method is called when the database schema version changes, allowing you to
upgrade database to new version without data loss.
SQLite API
Example
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="student.db";
private static final int DATABASE_VERSION=1;
public DBHelper(Context context)
{
super(context,DATABASE_NAME,null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
//create table and schema here.
db.execSQL("CREATE TABLE student(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//implement database upgrade logic here...!
db.execSQL("DROP TABLE IF EXISTS student"); //deletes existing table “student”
onCreate(db); //called to recreate the database.
}
}
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Database Example"
android:textSize="25sp"
android:gravity="center"
android:textStyle="bold"/>
<EditText <Button
android:id="@+id/et1" android:layout_width="160dp"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_height="60dp" android:id="@+id/save"
android:hint="Student Name"/> android:textSize="20sp"
<EditText android:text="Save"/>
android:id="@+id/et2" <Button
android:layout_width="match_parent" android:layout_width="160dp"
android:layout_height="60dp" android:layout_height="wrap_content"
android:inputType="number" android:id="@+id/display"
android:hint="Score Obtained"/> android:textSize="20sp"
android:text="Display"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lv"/>

</LinearLayout>
activity_main.xml
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME="student.db";

private static final int DATABASE_VERSION=1;

public static final String TABLE_NAME="studentinfo";

public static final String COLUMN_ID="_id";

public static final String COLUMN_NAME="name";

public static final String COLUMN_SCORE="score";

public DBHelper(Context context)


{
super(context,DATABASE_NAME,null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{ DBHelper.java
String createQuery="CREATE TABLE "+ TABLE_NAME + " ("
+ COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_NAME +“ TEXT, "
+ COLUMN_SCORE +" INTEGER"
+")";
db.execSQL(createQuery);

} public void addDetails(String name, int score)


{
SQLiteDatabase db=this.getWritableDatabase();

String insertQuery="INSERT INTO "+ TABLE_NAME +


" ("+COLUMN_NAME+", "+COLUMN_SCORE+") "
+"VALUES ("+"'"+name+"'"+", "+score
+")";
db.execSQL(insertQuery);
}
DBHelper.java
public Cursor displayDetails()
{
SQLiteDatabase db=this.getReadableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME,null);

}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//implement database upgrade logic here...!
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public class MainActivity extends AppCompatActivity {

DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

EditText et1=(EditText)findViewById(R.id.et1);

EditText et2=(EditText)findViewById(R.id.et2);

Button save=(Button)findViewById(R.id.save);

Button display=(Button)findViewById(R.id.display);

ListView lv=(ListView)findViewById(R.id.lv);

dbHelper=new DBHelper(MainActivity.this);
MainActivity.java
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if(!et1.getText().toString().isEmpty()&&!et2.getText().toString().isEmpty())
{
String sname = et1.getText().toString();
String str2 = et2.getText().toString();
int marks = Integer.parseInt(str2);

dbHelper.addDetails(sname, marks);

Toast.makeText(MainActivity.this,
"Record Added Successfully", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,
"Enter all details",Toast.LENGTH_LONG).show();
}
}
});
MainActivity.java
display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

Cursor cursor=dbHelper.displayDetails();

if (cursor != null && cursor.getCount() > 0) {


SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this,
R.layout.list_item,
cursor, new String[]{"_id", "name", "score"},
new int[]{R.id.textId, R.id.textName, R.id.textScore},
0);

lv.setAdapter(adapter);
}
else{
Toast.makeText(MainActivity.this,
"No Record found",Toast.LENGTH_LONG).show();
}
}
});
}//end onDestroy()
MainActivity.java
@Override
protected void onDestroy() {
super.onDestroy();
// Close the cursor if it's still open

Cursor cursor = dbHelper.displayDetails();

if (cursor != null && !cursor.isClosed())


{
cursor.close();
}
}
}
MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textId"
android:text="Id"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textName"
android:text="Name"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textScore"
android:text="Score"/>

</LinearLayout>
Thank You

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy