Nothing Special   »   [go: up one dir, main page]

MAD Assignment Answers

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Answers:

Q 5.1: Explain file handling in android. (10 M)

Answer:

Persistent Data:

 Persistent data is one which reside on nonvolatile storage like SD card, internal memory etc.
 Persistent data remains preserved irrespective of execution state of application.

File Handling using native java api’s:

 Files are stored on external sd card or internal memory of device


 Files can be either of 3 types
o Simple file
o Directory
o Special files like dev, Pipes etc.
 In android, files are handled in two ways.
o Files on internal storage
o Files on External storage
1. Internal Storage:
Writing contents to internal storage file:
 Those are the files that acts as a private data of application and created in
applications installation directory.
 file remains accessible to application until application exist on device, once application
is removed files on internal storage are destroyed from device
 Files are written to internal storage using FileOutputStream instance generated by method
“openFileOutput()” method.
 Files are processed in 3 steps
o Opening connection to file using Stream classes
o Operating on files(either reading or writing contents )
o Closing connection to file using close() method
 Syntax of openFileInput():
o FileOutputStream fos=openFileOutput("sample.txt", MODE_PRIVATE);

Reading contents on internal storage Files:

 Create InputStream to file using method OpenFileInput(“FileName”)


 Perform reading operation using read() method
 Close file
 Methods on InputStream:
1. Available() :returns remaining bytes in file to read
2. Read( byte[]) : read bytes from file equivalent to size of Byte array
2.External storage:

 Files stored on externally mounted storage device like sd card and which is not part
of application specific directory is called external storage file.
 Before using external storage through programming api’s application need
“android.permission.WRITE_EXTERNAL_STORAGE” permission.
 Before using external storage, its availability can be verified using
“getExternalStorageState()” method, if storage is available method
returns MEDIA_MOUNTED constant.
 There are two alternative to create external storage directory
o In public folder :

files available in shared manner to other applications.


Directory location obtained using
getExternalStoragePublicDirectory( Environment.DIRECTO
RY_PICTURES), albumName);

o Private application folder:

Files In this folder will not be accessible to other applications.


Directory location can be obtained by getExternalFilesDir()

Files can be deleted using File.delete() method in java.io.

Q 5.2 What is shared preference ? explain in detail all methods in shared preference.
Explain scenario when shared preference is useful.(10 Marks)

Anwer:

SharedPreference:

 It is an xml file which can store semistructured data in the form of key and value pairs.
 Share preferences files are used when data managed by application is small in volume and
no complicated operations are needed to be performed on data.
 For many application these files are useful to save configuration information about use
preferences of application setting like background of app, theme, font specifications
etc.
 Any application component can read or update the shared preference file.

Accessing Shared Preferences File:

Accessed for three purposes


1.Writing /updating shared preference file
2.Reading SharedPreference file
3.Deleting all contents in SharedPreference File
1. Writing Contents in SharedPreferences File : 3 steps
1. Creating /Opening SharedPreferenc file by creating instance of SharedPreference class
SharedPreference
sh=Context.getSharedPreference("fname",
Mode)
Modes:
MODE_PRIVATE: No other application is allowed to access file
MODE_WORD_READABLE/MODE_WORLD_WRITEABLE:
Other application available with file identifier can access the file.
2. Create object of Editor class (Nested class defined in SharedPreference) and
write contents to preferences file using putXXX() method. Where XXX can be
any java primitive/ nonprimitive data type like int,float, char ,String etc.
3. To save changes on persistent storage , call commit on editor instance.eg.
4. To remove elements from file, invoke remove(key) method
SharedPreferences sh=
Context.getSharedPreferences("commands",MODE_PRIVATE)
; Editor ed=sh.edit();
ed.putString("location","getLocation");
ed.putString(“call”,”callme”);
ed.remove(“call”);
ed.commit();

2. Reading contents from Shared preference file:


o Create instance of SharedPreferences class instance.
SharedPreference sh=Context.getSharedPreference("fname",Mode)
o Invoke getXXX(“key”,”default_value”) method on SharedPreference Instance,
default value represent value to returned by method when no key exist in a file.
o Eg . SharedPreference
sh=Context.getSharedPreference("commands",MODE_PRIVATE)
; sh.getString(“call”,”No command exist”);
sh.getString(“location”,”no location key exist”);
3. Deleting all elements in SharedPreference file.
Creating /Opening SharedPreferenc file by creating instance of SharedPreference
class
Create object of Editor class.
Invoke Editor.clear() method.
Invoke Editor.commit()
SharedPreferences sh=
Context.getSharedPreferences("commands",MODE_PRIVATE)
; Editor ed=sh.edit();
ed.clear();
ed.commit();

Q 5.4: What is relational data? Explain features of Sqlite. (5

M): Relational Data:


 Data that can be expressed in terms of rows and columns is called relational data.
 Relation is tabulated representation of data on which relational operations can be applied.
 Relational operational are integral part of any dbsm application.

Sqlite

 it is client side ,open source light weight dbms application designed for portable
low configuration handheld devices.

Sqlite Features:

 Client side,open source dbms application.


 Provides almost all features of basic relational DBMS software like transaction support,
query engine.
 It needs around 250k memory. By virtue of its low memory requirement, it is used in wide
range of handheld devices.
 It supports data types like integer,real ,text, NULL, blob etc.
 It support weakly types data storage mechanism.
 In weekly type storage mechanism , user is free to store any type of data in any type of
variable, no run time type checking is performed. Eg. in integer variable string can be stored at
run time.
 In android devices , it is available as an integrated application
 It doesn’t provide server side administration, foreign key constraint and complex join operation.
 All tables created by sqlite api are stored at location “data/data/APP_NAME/databases/” directory

Sqlite Api:

 All relational operations are embedded in SqliteOpenHelper, SqliteDatabase


,Cursor, ContentValue classeses.
 Important operations in SqliteDatabase class are rawQuery(), query(), insert(),update(),delete()
etc.

Q 5.5 Explain Sqlite in detail.(10 M)

Sqlite

 it is client side ,open source light weight dbms application designed for portable
low configuration handheld devices.

Sqlite Features:

 Provides almost all features of basic relational DBMS software like transaction support,
query engine.
 It needs around 250k memory. By virtue of its low memory requirement, it is used in wide range
of handheld devices.
 It supports data types like integer,real ,text, NULL, blob etc.
 It support weakly types data storage mechanism.
 In android devices , it is available as an integrated application
 It doesn’t provide server side administration, foreign key constraint and complex join operation.

All tables created by sqlite api are stored at location “data/data/APP_NAME/databases/” directory

Sqlite Api’s:

 in android ,all relational methods are accessible through two classes .


1. SqliteOpenHelper
2. SqliteDatabase

1.SqliteOpenHelper:

 Provides method to create database,action indicating the process after upgrading


database version(onCreate(),onUpgrade())
 Creating Database with SqliteOpenHelper constructor:
o
SQLiteOpenHelper(Context context, String databasename,
SQLiteDatabase.Curs orFactory factory, int version)
o Used to allow returning sub-classes of Cursor when calling query, when not applicable
null value should be provided
o Version: for current sqlite version is 1.
o Eg. SqliteOpenHelper(getApplicationContext(), “studentdb”,null,1);
 onCreate(SqliteDatabase arg0) :
o invoked as soon as database is created.
o This method is used to create tables if not existing using SqliteDatabase reference
as follows.
arg0.execSQL("create table if not exist student(rollnumber INTEGER PRIMARY
KEY AUTOINCREMENT,name TEXT);");

 onUpgrade()
o method defines postoperative action when database version is changed.
o Normally database table should be migrated from old version to new version format,
if not possible tables should be deleted and recreated.
 getWritable():
o returns writable instance of SqliteDatabase class.
o This instance can be used to perform insert,update,delete operations on database tables.
 getReadable():
o returns readable instance of SqliteDatabase object,it can be used to perform
select operation on database tables.

2. SqliteDatabase:

 provide methods to open, query ,update and close database.


 Provide adaptor method insert() , update(), delete(), query() to perform insert, update
delete, select operations resp. on database tables.
 Any update operation is possible by using writable instance of SqliteDatabase class and
select operation can be performed by using readable instance of it.
 to create Writable instance of SqliteDatabase
1. SqliteDatabase sqlitedatabase=dbhelper.getWritable();
 Step to create Readable instance of SqliteDatabase
1. SqliteDatabase sqlitedatabase=dbhelper.getReadable();
Steps to operate on table in Android using sqlite api
2. Create readable /writable instance of SqliteDatabase class based upon type of operation
to perform.
3. Perform operations using adaptor methods(insert,update,delete,query) or rawQuery()
methods.
4. Close connection to database using sqlitedatabase.close().
Adaptor methods :
5. insert(tablename, nullColumnHack, ContentValueObject)
ContentValue is an object which stores values in the form of key and value pair
Key for database program is name of column and value is column value
Eg. If student is table with 3 columns , rollnumber , name and marks
content value can be created and inserted as

6. query(String tablename, String[] columns, String selection, String[] selectionArgs,


String groupBy,String having, String orderBy, String limit)
Query the given table and return the object of Cursor.
Cursor provide several methods to return properties of ResultSet, to
control position of row referred by Cursor.
7. delete():
delete(“tablename”,”criteria”, selection_arguement_string_array)
criteria can be any valid condition returning Boolean value eg. name=’raj’
8. update():
update(table_name,ContentValueObject,Selection_Condition,ColumnsList)
ContentValue is container object holding key value for specific columns to
be replaced in columnlist.
Selection_condition represent Boolean condition for indicates rows to
be updated.

Q 5.6. Explain use of Cursor and ContentValue class.(5 M)

1. ContentValue:
 ContentValue instance is an object which stores values in the form of key and value pair
 This object represent entire row /part of row that has to be inserted/updated in
database tables.
 Key for database program is name of column and value is column value
 Eg. If student is table with 3 columns , rollnumber , name and marks content value can
be created and inserted as

ContentValue contentvalue=new ContentValue();


contentvalue.putInt(“rollnumber”,1)
contentvalue.putString(“name”,”raj”);
contentvalue.putInt(“marks”,40);
sqlitedatabase.insert(“student”,null,contentvalue)
;
2. Cursor:
 It is an object returned as a result of call to query() method in SqliteDatabase instance.
 Represent reference to list of extracted columns in table.
 It provides methods for navigating through output table, retrieving table properties like
getting number of rows,columns, column indexes, columns names with specific
indexes
etc.
i. Methods to control position of Cursor:
1. moveToFirst() position cursor to first row of result set.
2. movleToLast() position cursor to last element of Result set.
3. moveToNext() move cursor to next row in the result set.
4. moveToPrevious() move cursor to previous row
5. moveToPosition(int position) move cursor to specified row position
ii. Methods to get properties of ResultSet of query methods.
1. getPosition() get current Cursor position of row set
2. getCount()returns number of rows in row set
3. getColumnCount()returns number of columns in row set
4. getColumnIndex(column name) return index of column with given
name
5. getColumnName(column index) return name of column with specified
index
iii. Methods to access element at particular column index
1. getXXX(column index) returns element at specified column index
referred by cursor object. XXX can be any primitive type or String
2. eg. getString(), getInt(), getFloat() etc.

Q 6.1 what is drawable? Explain canvas in detail.

(5M) Drawable:

 any graphical file which can be represented in android via Bitmap drawable class.
 Drawable can be image or shape located in res/drawable folder.
 Based upon image resolution, it can be located in ldpi, hdpi, mdpi or xhdpi folder.
Canvas:-Refer anubhav pradhan book

Q 6.2. explain drawable animation in detail.(5M)

Animation:

 Animation is a process in which any drawable object/view element or its property is


changed with respect to time.
Drawable: is resource which can be drawn on view. It can be bitmap image or shape defined
by xml file.

Drawable Animation:changing series of drawable in quick succession of time is called


drawable animation.

 Entire animation process is expressed in separate xml file which defines drawable
resources to be moved, duration for which each resource should be visible.
 Steps to Create Drawable Animation

1. copy images in drawable folder

2. create xml file drawableanim.xml in drawable folder with animation-list as root element

<animation-list>

<item location,interval>

</animation-list>

3. add images resources an item in xml file with display duration

4. in MainActivity create handle to imageView

5. set imageview resource to null

6. set backgroundresource of imageview to xml file

7. create object of AnimationDrawable using

method ad=iv.getBackground();

8.start animation using AnimationDrawable

object ad.start()

 Program( onCreate() method In java file):

//step 4
iv=(ImageView) findViewById(R.id.imageView1);
//step 5
iv.setImageDrawable(null);
//step 6:set background prop of iv to anim file
iv.setBackgroundResource(R.drawable.drawableanim)
;

//step 7,8:create Drawable anim object and start


animation ad=(AnimationDrawable) iv.getBackground();
ad.start();
Q 6.3 explain View animation with example.

(5M) Animation:

 Animation is a process in which any drawable object/view element or its property is


changed with respect to time.

View Animation:

 It is applicable to single view element and not for multiple objects.


 In this ,either of the following four effect can be generated on view and view property can
be changed with respect to time.
Sr. Effect Xml tag Important properties
No. element
1 Scaling <scale> fromXScale,toXScale,fromYScale,toYScale,duration
2 Translation <translate> fromXDelta,toXDelta, duration
3 Rotation <rotate> formDegrees, toDegrees,pivotX,pivotY, duration
4 Transparency <alpha> fromAlpha, toAplha, duration
change

Steps to Create View Animation:

step 1: create anim folder ,inside create xml file describing properties to be changed for view animation

step 2: inside activity class create object of Animation

Animation animation=AnimatioinUtils.loadAnimation(xmlfilename);

step 3:on image view call startAnimation method and pass Animation object as

parameter iv.startAnimation(animation);

eg. program to scale view by twice of original dimension

//res/anim/scalinganim.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="1.0"
android:toXScale="2.0"
android:fromYScale="1.0"
android:toYScale="2.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000"/>

</set>

//java file code


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viw_animatioin_activy)
; iv=(ImageView) findViewById(R.id.imageView1);

}
public void startAnim(View v) throws InterruptedException
{
Animation scaling=AnimationUtils.loadAnimation(this, R.anim.scalinganim);
iv.startAnimation(scaling);
}

6.4 Explain Property Animation.(5 M)


Answer : Refere book Anubhav Pradhan-page No.-178,179

6.5 Explain Types of animation in detail.(10 M)


Answer : combine 6.1,6.2 and 6.3 without illustration of program.

6.6 explain MediaPlayer state diagram in detail(10 M)

Answer:

 Media player class can be used to control audio /video files and streams.
 Playback of audio/video files/streams is managed by state machine which indicates state
of media player device in different life cycle phases.

1. Idle : state retained when media player instance is just created.in this state it is not associated
with any media source.calling any method related to media source in this state results in
exception.
2. Initialized : media player instance variables are initialized to default values.
3. Prepare: associate media file/stream with media player. Stream /file can be residing in
resource folder, sd card or on web server. phase is analogous to loading dvd in dvd player.
Path of media must be provided to setDataSource() method which is implicitly called in this
state.media contents are decoded in this phase.
4. Start: in this state ,device starts reading codecs from media file, and music is played.
5. Pause : it suspend the media player . in this method state of playing actions is not maintained
by mediaplayer instance. Programmer can record current track using getCurrentPosition()
method and resume its playing action with seekTo(position) when media is restarted.
6. Stop: in this state , media player release data source and no same media can be played in current
life cycle by media player instance
7. Release : in this phase, media player instance is destroyed, it releases all the resources held
by instance eg. references to device files, stream/file connections etc.
Program to illustrate different states through method invocation:

protected void onCreate(Bundle savedInstanceState)

{ super.onCreate(savedInstanceState);

setContentView(R.layout.activity_music_a b_div);

mp=MediaPlayer.create(getApplicationContext(),

R.raw.janumerijaa);

//handler method for start button

public void startMusic(View arg) throws Exception


{
mp.prepare();

mp.start();

Toast.makeText(getApplicationContext(), "music
started", Toast.LENGTH_SHORT).show();

//handler method for stop button

click public void stopMusic(View

arg)

mp.stop();

mp.release();

6.7 Explain cell triangulation method .(5M)

 Cell tower transmit radio signal at regular interval to the devices available in hexagonal cell
area surrounding tower.
 Devices communicates continuously with tower once in 0.1second. So in simplest
scenario location of cell indicates location of device.
 Since cell covers large span of circular area, it will be difficult to determine location of
device within circumference of the cell.
 The advantage of network-based techniques, from a service provider's point of view, is that
they can be implemented non-intrusively without affecting handsets.
 Network-based techniques were developed many years prior to the widespread availability of
GPS on handsets.
 Accuracy with cell identification as the least accurate and triangulation as moderately accurate
 Triangulation is the process of determining the location of a point by forming triangles to it
from known points.
 it is the way of location device location using signal strength of nearest three towers.

6.8 Write a note on geocoding and reverse geocoding.(5 M)

Answer:

GeoCoding and reverse geocoding:

 Geocodes are standard mechanism to represent any location on the earth in terms of
latitude and longitude.
 Latitude and longitude are imaginary vertical and circular lines plotted around earth axis.
 Physical location of object can be represented by the pair of intersecting lattitutde
and longitude at the location of object
 Location={latitude,longitude}
 Since geocordinates cannot be understood by ordinary peoples who are aware physical location
identity consisting of city,pincode, lane etc.
 Mapping of geocoordinate physical location name is maintained in google map server and is
accessible through programming api’s .
 Translation of physical location to geocoordinate is called forward geocoding , and
translating geocoordinates to physical location is called reverse geocoding.
 Eg. {lat:12.77,long:14.155}-tale hipparaga,solapur ….reverse geocoding
{tale hipparaga,solapur}{lat:12.77,long:14.155} ….forward geocoding
 In android Geocoder class is provided to perform forward and reverse geocoding mechanisms.

6.9 Explain location based services in detail.(5 M)

Answer:

LocationBased Services:

 These are the services enables programmer/user to locate location of device in geographical
area in space, time dimensions.
 3 mechanism exist which act as location provider mechanisms for device users
o Cell based identification:
Mobile device continuously receive signal from nearest tower.
but single tower can cover long span circular are for signal transmission, so
within circumference again to identify exact position, weak signal from next
two towers are used.
Intersection area covered between three towers is returned as an approximate
device location in this mechanism.
These approach provides lowest accuracy ,lowest battery consumption and
involve low cost as signal transmission to and from GSM tower is continuos
action in device
o Using Wifi :
If wifi is enabled on device and device captures wifi signal, then location of
wifi network will be the same location of device.
Involve low accuracy, high battery consumtion and low cost
o GPS based location identification:
In this approach in built gps hardware is provided in device, which continuously
communicate its position to gps satellites.
GPS satellite are dedicated satellite to operate on locating all gps enabled
devices.
Mechanism provides highest accuracy of location, require extra power for
internal gps device and incur cost for internet connection.

6.9 Explain location based services in detail.(10 M)

Answer: combine explanation of previous two questions(6.8 and 6.9)

6.10 Explain Gps besed location finding mechanism in android.(5 M)

 Device location access needs various permission , important permissions are


1. android.permission.ACCESS_COARSE_LOCATION
2. android.permission.ACCESS_FINE_LOCATION
3. android.permission.INTERNET
 android.location package includes library classes and interfaces useful to retrieve
 Several classes and interfaces are provided in android library to access location of device
which are as follows.

Classes:

1. LocationManager:
a. Used to retrieve location list of different location provider available on device
<String>(getProviders())
b. Used to test whether specific provider for location identification is available or
not (isProviderEnabled(LocationManager.GPS_PROVIDER)) : function returns true
if device has gps and it is turned on
c. Returns best provider, matching constraints in Criteria object
(getBestProvider(Criteria obc,Boolean flag)
d. Returns last known location of device (getLastKnownLocation(provider)
e. Can set device to retriever regular location updates based on time interval and
distance changed from current location.
(requestLocationUpdate(provider,timeinms,distanceimmeter,location_listener)
2. Location:
Object returned as a result of getLastKnownLocation or as an argument to
locationchange activity.
a. getLatitude() : returns latitude of device as a double value
b. getLongitude(): returns longitude of device
3. Criteria:
a. Is an object used to specify the choice of location provider based upon
balanced combination of specific criteria values.
b. Those factors are
i. Accuracy:- ACCURACY_COARSE,ACCURACY_FINE
ii. Power requirement:-POWER_LOW, POWER_HIGH
iii. costAllowed:- true, false
4. Geocoder:returns different location parameters like city, area description,pincode
etc a. getMaxAddressLineIndex(): -returns max number of lines in address
b. getAddressLine(index):-returns address line with specified index
c. getFromLocation(lat,long,maxloc):-return Address object,consisting of fields
locality,city ,pincode etc.

Interface Used in location Update:

LocationListener:

Provides declaration of following methods.

1. onLocationChanged(Location arg):-whenever device location is changed by specific


distance value or timer interval is elapsed specified by user in
requestLocationUpdate(), this method is invoked.
2. onProviderDisabled():- invoked when particular provideder is disabled eg. gps is turned
off.
3. onProviderEnabled():-invoked when provider is enabled by user

Steps to Access Location Update from device through Program:

 create activity implementing LocationListerner interface. Listener provide several methods that
will be invoked on location update or during provider status change(eg. onLocationChanged(),
onProviderEnabled(), onProviderDisabled())
 create instance of LocationManager using getSystemServices(GPS_PROVIDER)
 implements onLocationChanged(Location) method.

6.10 Explain Gps besed location finding mechanism in android.(10 M)

Answer : combine explanation of 6.8 and 6.10

6.11 Explain types of sensors in android(5/10 M)

Sensor:

 It is component in device capable of detecting and measuring changes in certain parameters


inside device or outside the device.
 Wide variety of sensor can exist in device based upon its configuration eg.
gyroscope, accelerometer, proximity sensor etc.
 Each sensor generates data about change in parameters and returned as an output eg.
Accelerometer generates integer acceleleration values in X ,Y and Z direction,
gyroscope generates tilt angle of device as an real value etc.
 3 categories of sensors exist in device
1. Motion Sensors:
can detect and measure linear motion and angular motion of device.
Accelerometer can sense and measure acceleration of device in X,Y and Z
direction.
Eg. accelerometer and gyroscope
2. Position Sensors:
Detect position of device in the vicinity of object
Used to identify presence of object in the nearby region of device.
If object is found enough close , appropriate actions can be performed through
programming api’s. eg. proximity sensor lock device when phone is taken
close to face.
Magnetometer detect orientation of device with respect to earths magnetic field.
These category of sensors returns distance of device from specific object.
Eg. proximity sensor, NFC sensor etc.
3. Environmental Sensors:
These sensors can sense changes in external environmental factors like
ligh, sound, temperature etc.
1. Temperature Sensor:
o Able to sense change in temperature
2. Pressure Sensor:
o Can sene change in pressure
3. LIgh sensor:
o Can sense changes in brightness of surrounding light and
data can be used to act accordingly eg. to adjust optimal
screen resolution based upon external light

6.12 Explain sensor frame work in android (10 M)

Answer:

Sensor Manager Framework:

 Android provides api’s are provided to recognize sensors and operates on sensors data.
 Framework provides several classes and interfaces to determine list of available sensors in
device, to activate specific sensor, to read data from sensors whenever it find changes in certain
parameters, to determine power requirement of sensor and to deactivate sensor.
 Two classes exist in android which provide all those functionalities
1. SensorManager:
It can be instantiated by the context
method
getSystemServices(Context.SensorService
)
Can provide list of available sensors ((List)getSensorList(TYPE_ALL))
Can generate programming handle to specific sensor as
Sensor accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
Code to retrieve list of sensors
final SensorManager
sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> slist=sm.getSensorList(Sensor.TYPE_ALL);
tv.setText(List.toString());

2. SensorEventListener Interface:
This interface provides two abstract methods
 onSensorChanged() : invoked when sensor find change in data values
it was retrieving for specific parameter. Eg. for Accelerometer ,when
acceleration changes in any direction this method is called
 onAccuracyChanged() :
o invoked when accuracy of sensor reaches below
predefined threshold value.
3. Sensor:
Used to refer specific sensor and to operate on it to fetch data .
Act as programming handle to sensor to be operated.

Steps to listen data from sensors

 Create class implementing event SensorEventListener


 Create instance of SensorManager.
final SensorManager sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);

 Create instance of of particular Sensor using getDefaultSensor() method in SensorManager.


Sensor s=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

 Register sensor for listening events on it and once processing is over , unregister
it sm.registerListener(this, s, SensorManager.SENSOR_DELAY_FASTEST);
sm.unregisterListener(this);

Define onSensorChanged() and onAccuracyChanged()
methods. public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
Sensor s=arg0.sensor;
if(s.getType()==Sensor.TYPE_ACCELEROMETER)
{
Toast.makeText(getApplicationContext(), "mobile is in
motion", Toast.LENGTH_SHORT).show();
float x=arg0.values[0];
float =arg0.values[1];
float=arg0.values[2];
}
}

8.1 Explain in details steps to upload app on android play store OR Explain versioning ,signing
,packaging mechanism in detail. (10

M) Answer:

 To upload app on api store, user need to create playstore account with completion of
registration process at 25$ onetime cost.
 Uploading app involves following steps
1. Versioning
2. Signing app
3. Packaging

Versioning:

 Define version information for app.

 Versioning information is provided in manifest file and include version code and version name.

o Version Code :

Number assigned using deway decimal numbering, includes


hierarchical numbering system.

o versionName —

A string used as the version number shown to users. This setting can be specified
as a raw string or as a reference to a string resource.

The value is a string so that you can describe the app version as a
<major>.<minor>.<point> string, or as any other type of absolute or relative version
identifier. The versionName has no purpose other than to be displayed to users

Signing App:

 Android requires that all APKs be digitally signed with a certificate before they can be installed.

 A public-key certificate, also known as a digital certificate or an identity certificate, contains


the public key of a public/private key pair, as well as some other metadata identifying the
owner of the key (for example, name and location).

 The owner of the certificate holds the corresponding private key.

 signing tools like jarsigner attaches the public-key certificate to the APK
 A keystore is a binary file that contains one or more private keys.

 Strong password must be chosen for keysotore.

 We can sign app from the command line using standard tools from the Android SDK
and the JDK. To sign an app in release mode from the command line −

 Generate a private key using keytool


$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Packaging Android App to apk file:


 Android application can be exported to apk file using some of the utility tools. Before
converting app to apk ,some intermediate translation phases are involved.

 Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it has useful for
memory optimization and reduce the boot-up speed time

 AAPT(Android assistance packaging tool):it has useful to convert .Dex file to.Apk

 APK(Android packaging kit): The final stage of deployment process is called as .apk.

You might also like