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

unit 5

Uploaded by

susipriya129
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

unit 5

Uploaded by

susipriya129
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT V

ADVANCED APPLICATIONS IN ANDROID

Location based Services:


A location-based service (LBS) is a software service for mobile device applications that
requires knowledge about where the mobile device is geographically located. The application
collects geodata, which is data gathered in Real Time using one or more location tracking
technologies.
Location-based services integrate data from various resources, including Global Positioning
System (GPS) satellites, cellular tower pings and short-range positioning beacons, to provide
services based on the user's geographical location.
The Location Object
The Location object represents a geographic location which can consist of a latitude,
longitude, time stamp, and other information such as bearing, altitude and velocity. There are
following important methods which you can use with Location object to get location specific
information −

Sr.No. Method & Description

float distanceTo(Location dest)


1 Returns the approximate distance in meters between this location and the
given location.

float getAccuracy()
2
Get the estimated accuracy of this location, in meters.

double getAltitude()
3
Get the altitude if available, in meters above sea level.

float getBearing()
4
Get the bearing, in degrees.

double getLatitude()
5
Get the latitude, in degrees.

double getLongitude()
6
Get the longitude, in degrees.
float getSpeed()
7
Get the speed if it is available, in meters/second over ground.

Get the Current Location


To get the current location, create a location client which is LocationClient object, connect it
to Location Services using connect() method, and then call its getLastLocation() method.
This method returns the most recent location in the form of Location object that contains
latitude and longitude coordinates and other information as explained above. To have
location based functionality in your activity, you will have to implement two interfaces −
 GooglePlayServicesClient.ConnectionCallbacks
 GooglePlayServicesClient.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to
implement in your activity class −

Sr.No. Callback Methods & Description

abstract void onConnected(Bundle connectionHint)


This callback method is called when location service is connected to the
1
location client successfully. You will use connect() method to connect
to the location client.

abstract void onDisconnected()


2 This callback method is called when the client is disconnected. You will
use disconnect() method to disconnect from the location client.

abstract void onConnectionFailed(ConnectionResult result)


3 This callback method is called when there was an error connecting the
client to the service.

*******************************
Animation & Graphics:
Animation is the process of adding a motion effect to any view, image, or text. With the help
of an animation, you can add motion or can change the shape of a specific view. Animation
in Android is generally used to give your UI a rich look and feel. The animations are
basically of three types as follows:
1. Property Animation
2. View Animation
3. Drawable Animation
1. Property Animation
Property Animation is one of the robust frameworks which allows animation almost
everything. This is one of the powerful and flexible animations which was introduced in
Android 3.0. Property animation can be used to add any animation in the Checkbox, Radio
Buttons, and widgets other than any view. An animation defined in XML that modifies
properties of the target object, such as background color or alpha value, over a set amount of
time.
file location:
res/animator/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a ValueAnimator, ObjectAnimator, or AnimatorSet
resource reference:
In Java-based or Kotlin code: R.animator.filename
In XML: @[package:]animator/filename
syntax:
<set
android:ordering=["together" | "sequentially"]>

<objectAnimator
android:propertyName="string"
android:duration="int"
android:valueFrom="float | int | color"
android:valueTo="float | int | color"
android:startOffset="int"
android:repeatCount="int"
android:repeatMode=["restart" | "reverse"]
android:valueType=["intType" | "floatType"]/>

<animator
android:duration="int"
android:valueFrom="float | int | color"
android:valueTo="float | int | color"
android:startOffset="int"
android:repeatCount="int"
android:repeatMode=["restart" | "reverse"]
android:valueType=["intType" | "floatType"]/>

<set>
...
</set>
</set>
The file must have a single root element: either <set>, <objectAnimator>,
or <valueAnimator>. You can group animation elements together inside the <set> element,
including other <set> elements.

2. View Animation
View Animation can be used to add animation to a specific view to perform tweened
animation on views. Tweened animation calculates animation information such as size,
rotation, start point, and endpoint. These animations are slower and less flexible. An example
of View animation can be used if we want to expand a specific layout in that place we can
use View Animation. The example of View Animation can be seen in Expandable
RecyclerView.
There are two types of animations that you can do with the view animation framework:
 Tween animation: creates an animation by performing a series of transformations on a
single image with an Animation.
 Frame animation: creates an animation by showing a sequence of images in order
with an AnimationDrawable.

3. Drawable Animation
Drawable Animation is used if you want to animate one image over another. The simple way
to understand is to animate drawable is to load the series of drawable one after another to
create an animation. A simple example of drawable animation can be seen in many apps
Splash screen on apps logo animation.

Transition drawable
An XML file that defines a drawable that can cross-fade between two drawable resources.
Creates a Transition Drawable.
Inset drawable
An XML file that defines a drawable that insets another drawable by a specified distance.
This is useful when a view needs a background drawable that is smaller than the view's actual
bounds.
Clip drawable
An XML file that defines a drawable that clips another drawable based on this drawable's
current level value. Creates a ClipDrawable.
Scale drawable
An XML file that defines a drawable that changes the size of another drawable based on its
current level value. Creates a ScaleDrawable
Shape drawable.
An XML file that defines a geometric shape, including colors and gradients. Creates
a GradientDrawable.
Important Methods of Animation

Methods Description

This method will start the


startAnimation()
animation.

This method will clear the


clearAnimation() animation running on a specific
view.

*******************************

Media & Camera API:


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 the android.hardware.camera2 API
or camera Intent. 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
An intent action type of MediaStore.ACTION_IMAGE_CAPTURE or
MediaStore.ACTION_VIDEO_CAPTURE can be used to capture images or videos without
directly using the Camera object.

Building a camera app


Some developers may require a camera user interface that is customized to the look of
their application or provides special features. Writing your own picture-taking code can
provide a more compelling experience for your users.
The general steps for creating a custom camera interface for your application are as follows:
 Detect and Access Camera - Create code to check for the existence of cameras and
request access.
 Create a Preview Class - Create a camera preview class that
extends SurfaceView and implements the SurfaceHolder interface. This class
previews the live images from the camera.
 Build a Preview Layout - Once you have the camera preview class, create a view
layout that incorporates the preview and the user interface controls you want.
 Setup Listeners for Capture - Connect listeners for your interface controls to start
image or video capture in response to user actions, such as pressing a button.
 Capture and Save Files - Setup the code for capturing pictures or videos and saving
the output.
 Release the Camera - After using the camera, your application must properly release
it for use by other applications.
Camera hardware is a shared resource that must be carefully managed so your application
does not collide with other applications that may also want to use it.

Detecting camera hardware


If your application does not specifically require a camera using a manifest declaration, you
should check to see if a camera is available at runtime. To perform this check, use
the PackageManager.hasSystemFeature() method
*************************

Working with video and audio inputs in android:


Android has a built in microphone and camera through which you can capture audio
and video and store it , or play it in your phone. Android provides MediaRecorder class to
record audio or video.
MediaRecorder myAudioRecorder = new MediaRecorder();
After specifying the audio source and format and its output file, we can then call the two
basic methods prepare and start to start recording the audio.
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the MediaRecorder class that
allows you more control over audio and video recording.

S.No Method & description

setAudioSource()
1
This method specifies the source of audio to be recorded

setVideoSource()
2
This method specifies the source of video to be recorded

setOutputFormat()
3
This method specifies the audio format in which audio to be stored

setAudioEncoder()
4
This method specifies the audio encoder to be used

setOutputFile()
5 This method configures the path to the file into which the recorded audio is to be
stored

stop()
6
This method stops the recording process.

release()
7
This method should be called when the recorder instance is needed.

Example
import android.media.MediaPlayer;
import android.media.MediaRecorder;
public class MainActivity extends AppCompatActivity {
Button buttonStart, buttonStop, buttonPlayLastRecordAudio,
buttonStopPlayingRecording ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

buttonStart = (Button) findViewById(R.id.button);


buttonStop = (Button) findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button)findViewById(R.id.button4);

buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);

random = new Random();


}}

Output
*************************

Camera API:
These are the following two ways, in which you can use camera in your application
 Using existing android camera application in our application
 Directly using Camera API provided by android in our application
Using existing android camera application in our application
You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera
application installed on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above, there are other available Intents provided by MediaStore. They are
listed as follows

Sr.No Intent type and description

ACTION_IMAGE_CAPTURE_SECURE
1
It returns the image captured from the camera , when the device is secured

ACTION_VIDEO_CAPTURE
2
It calls the existing video application in android to capture video

EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape

4 EXTRA_FULL_SCREEN
It is used to control the user interface of the ViewImage

INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode

EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size

Now you will use the function startActivityForResult() to launch this activity and wait for its
result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity.
There are methods defined in the activity class that does the same job , but used when you are
not calling from the activity but from somewhere else. They are listed below

Sr.No Activity function description

startActivityForResult(Intent intent, int requestCode, Bundle options)


1
It starts an activity , but can take extra bundle of options with it

startActivityFromChild(Activity child, Intent intent, int requestCode)


2
It launch the activity when your activity is child of any other activity

startActivityFromChild(Activity child, Intent intent, int requestCode,


Bundle options)
3
It work same as above , but it can take extra values in the shape of bundle
with it

startActivityFromFragment(Fragment fragment, Intent intent, int


4 requestCode)
It launches activity from the fragment you are currently inside

startActivityFromFragment(Fragment fragment, Intent intent, int


requestCode, Bundle options)
5
It not only launches the activity from the fragment , but can take extra values
with it

*******************************
Sensor Programming:
Sensors can be used to monitor the three-dimensional device movement or change in
the environment of the device. Android provides sensor api to work with different types of
sensors.
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. These sensors measure acceleration forces and rotational forces along three axes. This
category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
 Motion sensors are useful for monitoring device movement, such as tilt, shake, rotation,
or swing.
 The movement is usually a reflection of direct user input, but it can also be a reflection of
the physical environment in which the device is sitting (for example, moving with you
while you drive your car).
 Motion sensors by themselves are not typically used to monitor device position, but they
can be used with other sensors, such as the geomagnetic field sensor, to determine a
device's position relative to the world's frame of reference.
 The rotation vector sensor and the gravity sensor are the most frequently used sensors for
motion detection and monitoring.
 The rotational vector sensor is particularly versatile and can be used for a wide range of
motion-related tasks, such as detecting gestures, monitoring angular change, and
monitoring relative orientation changes.
 Syntax
private SensorManager sensorManager;
private Sensor sensor;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

2) Position Sensors
These are used to measure the physical position of device. These sensors measure the
physical position of a device. This category includes orientation sensors and magnetometers.
Position sensors are useful for determining a device's physical position in the world's frame
of reference. For example, you can use the geomagnetic field sensor in combination with the
accelerometer to determine a device's position relative to the magnetic north pole. The
geomagnetic field sensor and orientation sensor return multi-dimensional arrays of sensor
values for each Sensor Event. For example, the orientation sensor provides geomagnetic field
strength values for each of the three coordinate axes during a single sensor event.
The geomagnetic field sensor lets you monitor changes in the earth's magnetic field. The
following code shows you how to get an instance of the default geomagnetic field sensor:
private SensorManager mSensorManager;

private Sensor mSensor;


...
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

3) 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. All four environment sensors are hardware-based and are
available only if a device manufacturer has built them into a device. With the exception of the
light sensor, which most device manufacturers use to control screen brightness, environment
sensors are not always available on devices. Because of this, it's particularly important that
you verify at runtime whether an environment sensor exists before you attempt to acquire
data from it.Unlike most motion sensors and position sensors, which return a multi-
dimensional array of sensor values for each Sensor Event, environment sensors return a
single sensor value for each data event.
Environment sensors that are supported on the Android platform.
Sensor Sensor event Units of Data description
data measure
TYPE_AMBIENT_TEMPERATURE event.values[0] °C Ambient air temperature.
TYPE_LIGHT event.values[0] Lx Illuminance.
TYPE_PRESSURE event.values[0] hPa Ambient air pressure.
TYPE_RELATIVE_HUMIDITY event.values[0] % Ambient relative humidity.
TYPE_TEMPERATURE event.values[0] °C Device temperature.

*******************************

Publishing Android Apps:


Android application publishing is a process that makes your Android applications
available to users. Infect, publishing is the last phase of the Android application development
process.

Android development life cycle


Here is a simplified check list which will help you in launching your Android application −

Step Activity

1 Regression Testing Before you publish your application, you need to make sure that
its meeting the basic quality expectations for all Android apps, on all of the devices
that you are targeting. So perform all the required testing on different devices
including phone and tablets.

Application Rating When you will publish your application at Google Play, you will
have to specify a content rating for your app, which informs Google Play users of its
2
maturity level. Currently available ratings are (a) Everyone (b) Low maturity (c)
Medium maturity (d) High maturity.

Targeted Regions Google Play lets you control what countries and territories where
3 your application will be sold. Accordingly you must take care of setting up time
zone, localization or any other specific requirement as per the targeted region.

Application Size Currently, the maximum size for an APK published on Google
Play is 50 MB. If your app exceeds that size, or if you want to offer a secondary
4
download, you can use APK Expansion Files, which Google Play will host for free
on its server infrastructure and automatically handle the download to devices.

SDK and Screen Compatibility It is important to make sure that your app is
5 designed to run properly on the Android platform versions and device screen sizes
that you want to target.

Application Pricing Deciding whether you app will be free or paid is important
6 because, on Google Play, free app's must remain free. If you want to sell your
application then you will have to specify its price in different currencies.

Promotional Content It is a good marketing practice to supply a variety of high-


7 quality graphic assets to showcase your app or brand. After you publish, these appear
on your product details page, in store listings and search results, and elsewhere.

Build and Upload release-ready APK The release-ready APK is what you you will
8 upload to the Developer Console and distribute to users. You can check complete
detail on how to create a release-ready version of your app: Preparing for Release.
Finalize Application Detail Google Play gives you a variety of ways to promote
your app and engage with users on your product details page, from colourful
9 graphics, screen shots, and videos to localized descriptions, release details, and links
to your other apps. So you can decorate your application page and provide as much
as clear crisp detail you can provide.

***************************
Guidelines, Policies and processes of uploading apps to Google Play:
Preparing your app for release is a multistep process involving the following tasks:
 Configure your app for release.
At a minimum, you need to make sure that logging is disabled and removed and that your
release variant has debuggable false for Groovy or isDebuggable = false for Kotlin script set.
You should also set your app's version information.
 Build and sign a release version of your app.
You can use the Gradle build files with the release build type to build and sign a release
version of your app. For more information, see Build and run your app.
 Test the release version of your app.
Before you distribute your app, you should thoroughly test the release version on at least one
target handset device and one target tablet device. Firebase Test Lab is useful for testing
across a variety of devices and configurations.
 Update app resources for release.
Make sure that all app resources, such as multimedia files and graphics, are updated and
included with your app or staged on the proper production servers.
 Prepare remote servers and services that your app depends on.
If your app depends on external servers or services, make sure they are secure and production
ready.
 Prepare promotional materials.
To fully leverage the marketing and publicity capabilities of Google Play, you need to create
promotional materials for your app such as screenshots, videos, graphics, and promotional
text.
 Configure options and uploading assets.
Google Play lets you target your app to a worldwide pool of users and devices. By
configuring various Google Play settings, you can choose the countries you want to reach, the
listing languages you want to use, and the price you want to charge in each country.
You can also configure listing details such as the app type, category, and content rating.
When you are done configuring options, you can upload your promotional materials and your
app as a draft app.
 Publish the release version of your app.
If you are satisfied that your publishing settings are correctly configured and your uploaded
app is ready to be released to the public, click Publish. Once it has passed Google Play
review, your app will be live and available for download around the world.
*****************************

You might also like