Unit-5 Notes - 250307 - 230640
Unit-5 Notes - 250307 - 230640
Marks-20
Course Outcome:
Create Android application using database.
Unit Outcomes:
5a. Apply the given Intents and service in Application development.
5b. Use Fragment to generate the given multiple activities.
5c. Develop programs to play the given multimedia.
5d. Write the query to perform the given database management operation.
Contents:
5.1 Intent, Intent Filter
5.2 Activity Lifecycle; Broadcast lifecycle
5.3 Content Provider; Fragments
5.4 Service: Features Of service, the Android platform service, defining new service, Service
Lifecycle, Permission, example of service
5.5 Android System Architecture, Multimedia framework, Play Audio and Video, Text to speech,
Sensors, Async tasks
5.6 Audio Capture, Camera
5.7 Bluetooth, Animation
5.8 SQLite Database, necessity of SQLite, Creation and connection of the database, extracting value
from cursors, Transactions.
5.1 Intent-
What is intent?
- Android uses Intent for communicating between the components of an Application and
also from one application to another application.
- Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc.
- Example: Intent facilitate you to redirect your activity to another activity on occurrence of
any event.
- By calling, startActivity() you can perform this task.
In android, Activity represents a single screen with a user interface (UI) of an application
and it will acts an entry point for users to interact with an app.
In android, Service is a component which keep an app running in the background to
perform long-running operations based on our requirements. For Service, we don’t have
any user interface and it will run the apps in the background like playing the music in the
background or handle network operations when the user in a different app.
Intent for Broadcast Receivers: There are various message that an app receives, these
messages are called as Broadcast Receivers. (For example, a broadcast message could be
initiated to intimate that the file downloading is completed and ready to use). Android
system initiates some broadcast message on several events, such as System Reboot, Low
Battery warning message etc.
Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent
Explicit Intent:
Explicit Intents are used to connect the application internally.
In Explicit, we use the name of component which will be affected by Intent.
Example: If we know class name then we can navigate the app from One Activity to another
activity using Intent. In the similar way we can start a service to download a file in background
process.
Explicit Intent work internally within an application to perform navigation and data
transfer. The below given code snippet will help you understand the concept of Explicit
Intents.
Example:-
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
Implicit Intent:
In Implicit Intents we do need to specify the name of the component.
We just specify the Action which has to be performed and further this action is handled by
the component of another application.
The basic example of implicit Intent is to open any web page.
Let’s take an example to understand Implicit Intents more clearly. We have to open a website
using intent in your application. See the code snippet given below.
Example-
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.google.com"));
startActivity(intentObj);
Example of Intent
Step 1: Design the UI of first activity activity_main.xml (it contains 2 buttons. 1st button to
execute explicit intent and 2nd button to execute implicit intent.)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation=”Vertical”>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/explicit_Intent"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/implicit_Intent"/>
</LinearLayout>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"/>
</LinearLayout>
Step 3: Implement onClick event for Implicit and Explicit Button inside MainActivity.java
MainActivity.java
package com.example.android.intents;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
ebtn = (Button)findViewById(R.id.explicit_Intent);
ibtn = (Button)findViewById(R.id.implicit_Intent);
}
}
SecondActivity.java
package com.example.android.intents;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<intent-filter attributes…….>
<elements ……..>
</intent-filter>
Attributes:-
1. android:icon
An icon represents the activity, service or broadcast receiver when a user interact with it.
To set an icon you need to give reference of drawable resource as:-
android:icon=“@drawable/icon”
How to add custom icon in your App:
Step 1: Open your android project folder in computer / system
Step 2: Open app>> src >> main >> res >> drawable >> here save custom icon image with
name
Step 3: Replace @drawable/icon with @drawable/your_image name in the below code
android:icon="@drawable/icon"
If you have not declared any icon for your activity then android sets the icon of parent
component by default.
And if no icon is defined by parent component then icon is set as the default icon by
<application> element (declared in Manifest file).
2. android:label
A label represents the title of an activity on the toolbar.
You can have different Labels for different Activities as per your requirement or choice.
The label should be set as a reference to a string resource.
However, you can also use a raw string to set a label as declared in the below given code
snippet
android:label = "@string/label"
or
android:label = "New Activity"
If you have not declared any label for your activity then it will be same as your parent
activity.
However if you haven’t declared any label to parent activity then label is set by
<application> element’ label attribute.
3)android:priority
The priority given to the parent component with regard to handling intents of the type
described by the filter.
This attribute has meaning for both activities and broadcast receivers.
It provides information about how an activity is to respond to an intent that matches the filter,
relative to other activities that can also respond to the intent.
When an intent can be handled by multiple activities with different priorities, Android
considers only those with higher priority values as potential targets for the intent.
It controls the order in which broadcast receivers are executed to receive broadcast
messages, with those having higher priority values being called before those having lower
values.
The value is an integer, such as 100. Higher numbers have a higher priority. The default value
is 0
A non-privileged application requests any priority >0.
A privileged application requests a priority >0 for ACTION_VIEW, ACTION_SEND,
ACTION_SENDTO or ACTION_SEND_MULTIPLE.
Important Note: Every intent filter must contain action element in it. Data and category
elements are optional for it.
1. 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 = "string" />
An Intent Filter element must contain one or more action element. Action is a string that
specifies the action to perform.
You can declare your own action as given below.
But we usually use action constants defined by Intent class.
<intent-filter>
<action android:name="com.example.android.intentfilters.Main2Activity"/>
</intent-filter>
There are few common actions for starting an activity like ACTION_VIEW
ACTION_VIEW: This is used in an Intent with startActivity(). This helps when you redirect to see
any website, photos in gallery app or an address to view in a map app.
For example: As we have done in previous example, we started a website using implicit intent in that
Intent we used ACTION_VIEW element to view website in the web browser.
2. Data:
There are two forms in which you can pass the data, using URI(Uniform Resource Identifiers) or
MIME type of data.
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. Check the below
given table for better clarification
3. Category:
This attribute of Intent filter dictates the behavior or nature of an Intent.
There is a string which contains some additional information about the intent which will be handled by
a component.
BROWSABLE – Browsable category, activity allows itself to be opened with web browser to open
the reference link provided in data.
LAUNCHER – Launcher category puts an activity on the top of stack, whenever application will
start, the activity containing this category will be opened first.
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
Method Description
onCreate() called when activity is first created.
onStart() called when activity is becoming visible to the user.
onResume() called when activity will start interacting with the user.
onPause() called when activity is not visible to the user.
onStop() called when activity is no longer visible to the user.
onRestart() called after your activity is stopped, prior to start.
onDestroy() called before the activity is destroyed.
The onCreate() and onDestroy() methods are called only once throughout the activity lifecycle.
The Activity lifecycle consists of 7 methods:
onCreate() : It is called when an activity is first created. When a user opens the app then some
Activity is created. You have to implement this method in every activity because, inside this
method, all the necessary components of your activity will be initialized. Here the initialization
of your application's UI is done.
onStart(): This method is called when an activity becomes visible to the user. When all the
initialization is done by the onCreate() method, then this method is called.
onResume(): It is called just before the user starts interacting with the application. Most of the
core functionalities of the app are implemented in this method.
onPause(): It is called when the activity is paused i.e. it is mostly called when you press the
back or home button of your Android device. It is an indication that the user is leaving the
activity and starting some other activity.
onStop(): It is called when the activity is no longer visible to the user. If you are starting a new
activity, or some existing activity is entering into
onResume() state, then the current activity will not be visible to the user and is stopped.
onRestart(): It is called when the activity in the stopped state is about to start again. By doing
so, the state of the activity from the time it was stopped will be restored.
onDestroy(): It is called when the activity is totally destroyed i.e. when you clear the
application stack then onDestroy() will be called and all the states of the activity will be
destroyed
Example
package com.example.activitylifecycledemo;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@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");
}
}
You will not see any output on the emulator or device. You need to open logcat.
Now click on the HOME Button. You will see onPause method is invoked.
Method Description
This method is used to send broadcasts to one receiver
sendOrderedBroadcast(Intent, String)
at a time.
This method is used to send broadcasts to all receivers
sendBroadcast(Intent)
in an undefined order.
This method is used to send broadcasts to receivers that
LoadBroadcastManager.sendBroadcast
are in the same app as the sender.
System Broadcasts
System events are defined as final static fields in the Intent class.
The following are some of the system events available in android applications.
Event Description
android.intent.action.BOOT_COMPLETED It raises an event, once boot completed.
It is used to trigger an event when power connected
android.intent.action.POWER_CONNECTED
to the device.
It is used to trigger an event when the power got
android.intent.action.POWER_DISCONNECTED
disconnected from the device.
It is used to call an event when battery is low on
android.intent.action.BATTERY_LOW
device.
It is used to call an event when a battery is OKAY
android.intent.action.BATTERY_OKAY
again.
android.intent.action.REBOOT It call an event when the device rebooted again.
5.3 Fragment
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/embedded in activity.
The FragmentManager class is responsible to make interaction between fragment objects.
There are 12 lifecycle methods for fragment.
Android Fragment Lifecycle Methods
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.
onCreateView(LayoutInflater,
3) creates and returns view hierarchy.
ViewGroup, Bundle)
4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.
It provides information to the fragment that all the saved
5) onViewStateRestored(Bundle)
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.
allows the fragment to do final clean up of fragment
11) onDestroy()
state.
It is called immediately prior to the fragment no longer
12) onDetach()
being associated with its activity.
<fragment
android:id="@+id/fragment1"
android:name="example.javatpoint.com.fragmentexample.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/fragment2"
android:name="example.javatpoint.com.fragmentexample.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
fragment_fragment1.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fragmentexample.Fragment1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is First Fragment" />
</FrameLayout>
fragment_fragment2.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fragmentexample.Fragment2">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is Second Fragment" />
</FrameLayout>
MainActivity.java
package com.example.fragmentexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Fragment1.java
package com.example.fragmentexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
Fragment2.java
package com.example.fragmentexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}
List of methods which you need to override in Content Provider class to have your Content
Provider working –
onCreate() - This method will initialize our provider. The android system will call this method
immediately after it creates our provider.
query() - It receives a request from the client. By using arguments it will get a data from requested
table and return the data as a Cursor object.
insert() - This method will insert a new row into our content provider and it will return the content
URI for newly inserted row.
delete() - This method will delete the rows in our content provider and it return the number of rows
deleted.
update() - This method will update an existing rows in our content provider and it return the number
of rows updated.
getType() - This method will return the MIME type of data to given content URI.
Content URIs
- In android,Content URI is an URI which is used to query a content provider to get the required
data. The Content URIs will contain the name of entire provider (authority) and the name that
points to a table (path).
2. Background Services:
- Background services do not require any user intervention.
- These services do not notify the user about ongoing background tasks and
users also cannot access them.
- The process like schedule syncing of data or storing of data fall under this service.
3. Bound Services:
- This type of android service allows the components of the application like
activity to bound themselves with it.
- Bound services perform their task as long as any application component is
bound to it.
- More than one component is allowed to bind themselves with a service at a time.
- In order to bind an application component with a service bindService() method is
used.
Example
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="pause" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop" />
</LinearLayout>
MainActivity.java
package com.example.audioplayerdemo;
import android.media.MediaPlayer;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.audioplayerdemo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start=(Button)findViewById(R.id.button1);
Button pause=(Button)findViewById(R.id.button2);
Button stop=(Button)findViewById(R.id.button3);
MediaPlayer mp=MediaPlayer.create(this,R.raw.bb3);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
}
});
}
}
public void setVideoURI (Uri uri) sets the URI of the video file.
activity_main.xml
<VideoView
android:id="@+id/vdVw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start" />
</LinearLayout>
MainActivity.java
package com.examples.videoplayerexample;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaController.setAnchorView(videoView);
//Location of Media File.
//Starting VideoView By Setting MediaController and URI
videoView.setMediaController(mediaController);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video1);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
});
}
}
Text to Speech App converts the text written on the screen to speech.
Text-to-speech is commonly used as an accessibility feature to help people who have trouble reading
on-screen text, but it’s also convenient for those who want to be read too.
This feature has come out to be a very common and useful feature for users.
Example-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:hint="Enter Any Sentence" />
<Button
android:layout_width="wrap_content"
android:id="@+id/btnText"
android:layout_height="wrap_content"
android:text="Click Here"
android:layout_gravity="center"/>
</LinearLayout>
MainActivity.java
package com.example.texttospeechdemo;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.speech.tts.TextToSpeech;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.texttospeechdemo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
Text = findViewById(R.id.Text);
btnText = findViewById(R.id.btnText);
btnText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textToSpeech.speak(Text.getText().toString(),TextToSpeech.QUEUE_FLUSH,null);
}
});
}
}
Android - Sensors
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.
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.
Android Sensor API
Android sensor api provides many classes and interface. The important classes and interfaces of
sensor api are as follows:
1. SensorManager Class: Sensor manager is used to accessing various sensors present in the
device.
2. Sensor Class: The sensor class is used to get information about the sensor such as sensor name,
sensor type, sensor resolution, sensor type, etc.
3. SensorEvent class: This class is used to find information about the sensor.
4. SensorEventListener interface: This is used to perform some action when sensor accuracy
changes.
Example to display list of sensors
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/sensorslist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sensors"/>
</LinearLayout>
MainActivity.java
package com.example.sensorsexample;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;
SensorManager mgr=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
TextView txtList = (TextView)findViewById(R.id.sensorslist);
List<Sensor> sensorList = mgr.getSensorList(Sensor.TYPE_ALL);
StringBuffer s1=new StringBuffer();
for(Sensor s: sensorList)
{
s1.append(s.getName()+"\n");
}
txtList.setVisibility(View.VISIBLE);
txtList.setText(s1);
}
}
<Button
android:id="@+id/cbutton"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:text="Camera" />
<ImageView
android:id="@+id/cimage"
android:layout_width="350dp"
android:layout_height="450dp"
android:layout_marginStart="30dp"
android:layout_marginTop="70dp"
android:layout_marginBottom="10dp" />
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb = findViewById(R.id.cbutton);
ci = findViewById(R.id.cimage);
cb.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent c=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(c);
}
});
}
if (requestCode == pic_id)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ci.setImageBitmap(photo);
}
}
}
5.7 Android Animation
Animation is the process of adding a motion effect to any view, image, or text.
With the help of an animation, you can add motion or can change the shape of a specific view.
Animation in Android is generally used to give your UI a rich look and feel.
The animations are basically of three types as follows:
Property Animation
View Animation
Drawable Animation
1. Property Animation
Property Animation is one of the robust frameworks which allows animation almost everything.
2. View Animation
View Animation can be used to add animation to a specific view to perform tweened animation on
views.
3. Drawable Animation
Drawable Animation is used if you want to animate one image over another. A simple example
of drawable animation can be seen in many apps Splash screen on apps logo animation.
clearAnimation() This method will clear the animation running on a specific view.
Second parameter refers to our animation.xml file. It is created under res directory (res->anim-
>myanimation.xml)
Property Animation:
This animation was introduced in Android 3.0 (API level 11). It allows the user to animate
anything.
Property animations are highly customizable, you can specify the duration, the number of
repeats, the type of interpolation, and the frame rate of the animation.
The Property Animation system is always preferred for more complex animations.
Common properties commonly animated on views include:
Property Description
alpha Fade in or out
rotation, rotationX, rotationY Spin or flip
scaleX ,scaleY Grow or shrink
x,y,z Position
translationX, translationY, translationZ Offset from Position
Example
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/rose1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade"
android:id="@+id/button1"
android:onClick="fade"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clockwise"
android:id="@+id/button2"
android:onClick="clockwise"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Move"
android:id="@+id/button3"
android:onClick="move"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blink"
android:id="@+id/button4"
android:onClick="blink"/>
</LinearLayout>
MainActivity.java
package com.example.animatedemo;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.animatedemo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
Right click res. Select Directory. Name it as anim. Right click ‘anim’ directory and select file, give
name such as clockwise.xml and copy below code.
A container that holds other animation elements (<alpha>, <scale>, <translate>, <rotate>) or
other <set> elements. Represents an AnimationSet.
clockwise.xml
<?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"
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>
fade.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000" >
</alpha>
<alpha
android:fromAlpha="1"
android:toAlpha="0"
android:duration="2000" >
</alpha>
</set>
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"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
move.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
slide.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<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>
5.7 Bluetooth
In Android devices, Bluetooth is a communication network protocol that allows devices to connect
wirelessly to exchange data with other Bluetooth devices.
In general, we can make use of Bluetooth API to implement Bluetooth functionalities, such as
enabling or disabling Bluetooth, searching for available Bluetooth devices, connecting with the
devices, and managing the data transfer between devices within the range.
In Android, the BluetoothAdapter class performs all Bluetooth-related activities.
By default, and Bluetooth device is in an undiscoverable mode.
This means that if we switch on the Bluetooth in a device, it is visible only to those paired earlier
with it. This device is invisible on devices other than the paired ones.
To make this device visible, we switch on the Discoverable option, which makes the device global to
its vicinity.
Android Set Bluetooth Permissions
To use Bluetooth features in our android applications, need to add multiple permissions, such
as BLUETOOTH and ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION in our
manifest file.
Permission Description
LOCATION We need this permission because the Bluetooth scans can be used to
gather the information about the location of user.
Following is the example of defining the Bluetooth permissions in android manifest file.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>
if(!bAdapter.isEnabled())
{
Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(eintent, intVal);
}
If you observe above code snippet, we used startActivityForResult() method
with ACTION_REQUEST_ENABLE intent action parameter to enable a Bluetooth.
The second parameter intVal in startActivityForResult() method is a locally defined integer that
must be greater than 0 and the system will return this parameter back to us
during onActivityResult() implementation as a requestCode parameter.
To know more about to TURN ON / OFF Bluetooth in android applications, check this Android
Bluetooth Turn ON / OFF with Examples.
To know more about device discoverability, check this Android Bluetooth Device Discoverability with
Examples.
If you observe above code, we are getting the Bluetooth paired devices name and mac address by
using BluetoothDevice object.
To know more about Bluetooth pair devices, check this Android Bluetooth List Pair Devices with
Examples.
This is how we can use Bluetooth in android applications to allow a devices to connect wirelessly to
exchange the data with other Bluetooth devices.
BluetoothAdapter class
By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate device
discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket instance to listen for
connection requests etc.
String ACTION_REQUEST_ENABLE
String ACTION_REQUEST_DISCOVERABLE
String ACTION_DISCOVERY_STARTED
String ACTION_DISCOVERY_FINISHED
<Button
android:id="@+id/BtBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click" />
<TextView
android:id="@+id/BtTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/BtBtn"
android:layout_centerHorizontal="true"
android:hint="Bluetooth Status"
android:textSize="30sp" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wifi">
<!--Put the permissions between the manifest and application opening tags-->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android: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>
</application>
</manifest>
MainActivity.java
import android.bluetooth.BluetoothAdapter
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
Android Bluetooth Example: enable, disable and make discovrable bluetooth programmatically
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/btnDiscoverable"
android:text="Turn ON" />
<Button
android:id="@+id/btnDiscoverable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Discoverable" />
<Button
android:id="@+id/btnOFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btnDiscoverable"
android:text="Turn OFF" />
</RelativeLayout>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth"
android:versionCode="1"
android:versionName="1.0" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bluetooth.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
MainActivity.java
package com.example.bluetooth;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mBluetoothAdapter.disable();
//out.append("TURN_OFF BLUETOOTH");
Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_LO
NG).show();
}
});
}
5.8 SQLite
SQLite is a Structure query base database, open source, light weight, no network access and
standalone database. It support embedded relational database features.
The main package is android.database.sqlite that contains the classes to manage your own
databases.
In order to create a database you just need to call this method openOrCreateDatabase()
with your database name and mode as a parameter. It returns an instance of SQLite database
which you have to receive in your own object.
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
We can create table or insert data into table using execSQL method defined in
SQLiteDatabase class.
Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Stud
We can retrieve anything from database using an object of the Cursor class.
Cursor resultSet = mydatbase.rawQuery("Select * from Stud_rec",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
Methods of Cursor
getColumnCount()
This method return the total number of columns of the table.
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column
getColumnNames()
This method returns the array of all the column names of the table.
getCount()
This method returns the total number of rows in the cursor
Example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="Insert Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="@+id/textView"
android:gravity="center"
android:textSize="20dp"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid"
android:layout_below="@+id/textView"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"
android:layout_below="@+id/editid"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"
android:layout_below="@+id/editname"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:lines="3"
android:id="@+id/editaddress"
android:layout_below="@+id/editmobile"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>
<Button
android:text="Insert Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editpincode"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
<TextView
android:text="Search Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:id="@+id/textView1"
android:gravity="center"
android:textSize="20dp"
android:layout_below="@+id/button"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter ID"
android:id="@+id/editsearchid"
android:layout_below="@+id/textView1"/>
<Button
android:text="Search Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editsearchid"
android:layout_centerHorizontal="true"
android:id="@+id/button1" />
</RelativeLayout>
MainActivity.java
package com.example.dbdemo5;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.dbdemo5.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
SQLiteDatabase sqLiteDatabaseObj;
EditText editTextID, editTextName, editMobileNo, editAddress, editPincode, editSearchid;
String cid, cname, cmobile, caddress, cpincode, sql_query, sid;
Button EnterData, SearchData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EnterData = (Button)findViewById(R.id.button);
SearchData = (Button)findViewById(R.id.button1);
editTextID = (EditText)findViewById(R.id.editid);
editTextName = (EditText)findViewById(R.id.editname);
editMobileNo = (EditText)findViewById(R.id.editmobile);
editAddress = (EditText)findViewById(R.id.editaddress);
editPincode = (EditText)findViewById(R.id.editpincode);
editSearchid = (EditText)findViewById(R.id.editsearchid);
EnterData.setOnClickListener(new View.OnClickListener() {
SearchData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sid = editSearchid.getText().toString();
Cursor cursor = sqLiteDatabaseObj.rawQuery( "select * from cTable where cid="+sid+"",
null );
if(cursor.getCount()==0)
Toast.makeText(MainActivity.this, "No Record found",
Toast.LENGTH_SHORT).show();
else {
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()) {
String cid = cursor.getString(0);
String name = cursor.getString(1);
String mob = cursor.getString(2);
String addr = cursor.getString(3);
String pcode = cursor.getString(4);
buffer.append(cid + " " + name + " " + mob + " " + addr + " " + pcode + "\n");
Toast.makeText(getApplicationContext(), buffer, Toast.LENGTH_LONG).show();
}
}
}
});
}
}