Professional Documents
Culture Documents
Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc. It is generally used with startActivity() method to invoke
activity, broadcast receivers etc.
1) Implicit Intent
It doesn't specify the component. In such case, intent provides information of available components
provided by the system that is to be invoked.
2) Explicit Intent
It specifies the component. In such case, intent provides the external class to be invoked.
An Android activity is one screen of the Android app's user interface. In that way an Android activity
is very similar to windows in a desktop application. An Android app may contain one or more
activities, meaning one or more screens. The Android app starts by showing the main activity, and
from there the app may make it possible to open additional activities.
Android service is a component that is used to perform operations on the background such as
playing music, handle network transactions, interacting content providers etc. It doesn't has any UI
(user interface).The service runs in the background indefinitely even if application is
There can be two forms of a service.The lifecycle of service can follow two different paths: started or
bound.
1. Started
2. Bound
1) Started Service
A service is started when application component (like activity) starts or calls startService() method,
now it runs in the background indefinitely. It is stopped by stopService() method. The service can
stop itself by calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. A bound
service offers a client-server interface that allows components to interact with the service, send
requests, get results, and even do so across processes with interprocess communication (IPC).The
client can unbind the service by calling the unbindService() method.The service cannot be stopped
until all clients unbind the service.
Android-powered devices have built-in sensors that measure motion, orientation, and various
environmental conditions. These sensors are capable of providing raw data with high precision and
accuracy, and are useful if you want to monitor three-dimensional device movement or positioning,
or you want to monitor changes in the ambient environment near a device.
These sensors measure acceleration forces and rotational forces along three axes. This category
includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
Environmental sensors
These sensors measure various environmental parameters, such as ambient air temperature and
pressure, illumination, and humidity. This category includes barometers, photometers, and
thermometers.
Position sensors
These sensors measure the physical position of a device. This category includes orientation sensors
and magnetometers.
Animation is the process of creating motion and shape change. Animation in android is possible in 3
ways:
1. Property Animations — They are used to alter property of objects (Views or non view objects).
We specify certain properties(like translateX, TextScaleX) of the objects to change. Various
characteristics of animation which can be manipulated are animation duration, whether to reverse
it and for how many times we want to repeat the animation etc. They were introduced in Android
3.0 (API level 11).
2. View Animations — They are used to do simple animations like changing size, position, rotation,
control transparency. They are easy to build and are very fast but have their own constraints. For
eg — Their state changes but their property does not change. View animations will be covered in
part 2.
3. Drawable Animations — This is used to do animation using drawables. An XML file specifying
various list of drawables is made which are run one by one just like a roll of a film. This is not
much used so I won’t cover it.
Text to speech, abbreviated as TTS, is a form of speech synthesis that converts text into spoken
voice output. Text to speech systems were first developed to aid the visually impaired by offering a
computer-generated spoken voice that would "read" text to the user. Android TTS API offers
PT-2 QB CO6I prepared by Poonam V Page 4
multiple-language support, control of voice characteristics and features, file output, and so on.
With just a small number of lines of code, you can make your apps reach out to a wider audience.
In android UI or input controls are the interactive or View components that are used to design the
user interface of an application. In android we have a wide variety of UI or input controls available,
those are TextView, EditText, Buttons, Checkbox, Progressbar, Spinners, etc.
Following is the pictorial representation of user interface (UI) or input controls in android
application.
Toggle button
A two state button that can be used as an alternative to a checkbox. It is particularly appropriate
where pressing the button will initiate an action as well as change a state. A toggle button allow the
user to change a setting between two states.
On state
Off state
Syntax
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="@string/toggle_turn_on"
android:textOff="@string/toggle_turn_off"
android:checked="true"
android:text="" />
1. Shared Preferences
You should use this to save primitive data in key-value pairs. You have a key, which must be a
String, and the corresponding value for that key, which can be one of: boolean, float, int, long or
string. Internally, the Android platform stores an app’s Shared Preferences in an xml file in a private
directory.
2. Internal Storage
The Internal Storage data storage method is specifically for those situations where you need to store
data to the device filesystem, but you do not want any other app (even the user) to read this data.
Data stored using the Internal Storage method is completely private to your application, and are
deleted from the device when your app is uninstalled.
3. External Storage
To save (and/or read) files to the device’s external storage, your app must request for the
WRITE_EXTERNAL_STORAGE permission. If you only want to read from the External Storage
without writing, request for the READ_EXTERNAL_STORAGE permission. The
WRITE_EXTERNAL_STORAGE permission grants both read/write access.
4. SQLite database
Finally, Android provides support for apps to use SQLite databases for data storage. Databases
created are app specific, and are available to any class within the app, but not to outside applications.
Android provides complete support for SQLite databases. The recommended way of creating SQLite
databases is to subclass the SQLiteOpenHelper class, and override the onCreate() method. For this
sample, we simply create a single table.
@Override
@Override
onCreate(sqLiteDatabase);
SQLite storage offers the power and speed of a full featured relational database to your app. If you
intend to store data that needs to be queried, you should consider using the SQLite storage option.
Watch out for our upcoming in-depth article on using sqlite storage in an android app.
These views can be used to create a useful input and output fields.
Text View
EditText
ImageView
CheckBox
RadioGroup
ListView
Spinner
Scrollview
AutoCompleteTextView
The android.widget.ScrollView class provides the functionality of scroll view. ScrollView is used
to scroll the child elements of palette inside ScrollView. Android supports vertical scroll view as
default scroll view. Vertical ScrollView scrolls elements vertically. Android
uses HorizontalScrollView for horizontal ScrollView.
1
float distanceTo(Location dest)
Returns the approximate distance in meters between this location and the given location.
2
float getAccuracy()
Get the estimated accuracy of this location, in meters.
3
double getAltitude()
Get the altitude if available, in meters above sea level.
4
float getBearing()
Get the bearing, in degrees.
5
double getLatitude()
Get the latitude, in degrees.
6
double getLongitude()
Get the longitude, in degrees.
7
float getSpeed()
Get the speed if it is available, in meters/second over ground.
8
boolean hasAccuracy()
True if this location has an accuracy.
9
boolean hasAltitude()
True if this location has an altitude.
10
boolean hasBearing()
True if this location has a bearing.
12
void reset()
Clears the contents of the location.
13
void setAccuracy(float accuracy)
Set the estimated accuracy of this location, meters.
14
void setAltitude(double altitude)
Set the altitude, in meters above sea level.
15
void setBearing(float bearing)
Set the bearing, in degrees.
16
void setLatitude(double latitude)
Set the latitude, in degrees.
17
void setLongitude(double longitude)
Set the longitude, in degrees.
18
void setSpeed(float speed)
Set the speed, in meters/second over ground.
19
String toString()
Returns a string containing a concise, human-readable description of this object.
The most common IDE for Android development is Android Studio, which comes directly from
Google itself.
After the installation of Android Studio, You also need to install Java on your machine to use
Android Studio. The JDK is able to interpret and compile your code for the application development.
Choose ‘Start a new Android Studio Project’ option. Enter the name you want for your application
and your ‘company domain’. All these elements will be used to create your package name in a format
like: com.companyname.appname
Moreover, you’ll be given the option to pick the way you want the app to look at the beginning. This
will be the look of your main ‘Activity Module’ which is basically the main page of your app. There
are various fields available which you have to choose according to your app needs, such as templates,
title, access to Google maps, full-screen activity, blank activity etc. As per my view, it’s better to go
for ‘Basic Activity’ to keep things as simple as possible and for all intents and purposes.
Now, you have to choose a layout name for the selected activity. This will define that where
elements like images and menus go and what fonts you’ll use. Choose a name for the menu and title
as well. Pick something attractive for the title, as your users will be able to see this at some points.
Go to the activity_main.xml tab if it is not open. Click and drag the “Hello, world!” from the upper
left corner of the phone display to the center of the screen. Then go to the values folder, and double-
click the strings.xml file. In this file, find the line “Hello world!” and add “Welcome to my App!”
In the Palette menu to the left of display, find Button. Click and drag Button to be positioned beneath
welcome message. Afterward, go to properties and find the field for text. Change the text from “New
Button” to “Next Page”.
Now go back to your content_main.xml and click on the button. In the right corner, where you have
your parameters for the button, you will catch an option called ‘onClick’. Click on this and then
select the ‘onClick’. By doing this, you have told Android Studio that you want to associate the
section of code with the button created.
Finally, all that’s missing to do is run the app you just made. Simple go to ‘run’ along the top and
then select ‘run app’ from the drop-down menu. Follow the steps to launch the emulator running
your app.
syntax:
14. Enlist (explain) the steps to publish the Android application. (if explain comes
in question write with explanation or else mention only steps. Also see the
weightage of marks if for 4 marks should write with explanation.)
1. Create an account
Firstly, To publish your app on google play store, you need to have account on google. You may
have already personal email account with them but for your app it's better to separate one for manage
your app(s) easily. You would have to pay a registration fees of 25 USD, using Google payments,
While registering your publisher account. After that, a verification mail would be sent to you and
then you sign in to your developer console, where all action would take place.
Developer console is starting point and main dashboard for publishing tools and operations. Before
you go ahead, familiarise yourself with list of merchant countries and developer countries. You need
to review list of merchant countries if you want to sell apps or in app purchases or have subscriptions
and list of developer countries will tell you about locations where distribution to Google play users is
supported. Apart from this, also looks the Google Play’s Terms and conditions.
After this, you have to provide your complete account details like you have to provide your
developer name, the name which would be displayed in Google Play Store. You will have to wait for
anything between just a little and 48 hours, after filling the details for Google play developer
registration to be processed.
If you have a paid app or subscription or in app purchases, then you have to inter link your google
payments merchant account and developer profile. It can be used for tax and financial identification
as well as monthly payout from sale.
When you are sign in your Google Play developer console, click on “Add new application” from
“All Applications tab”. After this select correct “Default Language” from drop down menu and then
type “title” of your app which would be appear on Google Play store. Then, select “Upload APK”
button to view on new page which would be your homepage for app. Time taken to upload file
depend on your app size. App will be in drafts until or unless you publish it.
It is essential to test it with sample of end users to get feedback of app before launch your app even
Google play take care of this as well. In section of your app “APK” of developer console, you will
find option related to “Alpha Testing” and “Beta Testing”. After you uploaded your app’s “APK” file
you can use these options for receive URL that can be shared with testers. By using this link, Testers
can download app beta or alpha version. Your testers can not provide reviews and feedback on app
page. Now you use this feedback to make relevant changes and optimise your app before publishing
in app store.
After uploading “APK” file go to “Store listing” tab. Over there you need to add details of app like
“Full description” and “Short description”. Along with this add categorisation, contact details, link of
promo video if you have, add screenshots and other necessary details to app. After complete
mandatory fields click on “Save” button. You can update your store listing anytime.
Now move on next tab, which is “Pricing and Distribution” and select it is “Paid” or “Free” app. You
also select distribution countries and check boxes stating your app complies with content guidelines.
If your app is an game one, then you can put in limelight using “Google Play for Game” option. Now
save changes and move on next step.
When all three tabs “Pricing and Distribution”, “Store Listing” and “APK” have been filled then
appear a green check mark next to them you are all ready to publish app in Google Play. After then
click on “Publish this app” button under “Ready to Publish” drop down menu at top right corner of
Developer console. A confirmation bar would show up stating your app would appear shortly in
Google Play Store.
There are series of extra option that might not seem to be important to publish the app but they can
prevent app from negative feedback. There is also option to manually filter non compatible devices
or problematic so make the most use of it to filter out any negativities and stay on the top.
ROADMAP (normal, default 2D map)− This is the default type. If you haven't chosen any of
the types, this will be displayed. It shows the street view of the selected region.
SATELLITE (photographic map)− This is the map type that shows the satellite images of
the selected region.
TERRAIN (map with mountains, rivers, etc.) − This is the map type that shows the terrain
and vegetation
16. Describe the types of permissions used while developing android applications.
Permissions are divided into several protection levels. The protection level affects whether runtime
permission requests are required. There are three protection levels that affect third-party
apps: normal, signature, and dangerous permissions.
Normal permissions
Normal permissions cover areas where your app needs to access data or resources outside the app's
sandbox, but where there's very little risk to the user's privacy or the operation of other apps. For
example, permission to set the time zone is a normal permission.
Signature permissions
The system grants these app permissions at install time, but only when the app that attempts to use a
permission is signed by the same certificate as the app that defines the permission.
Dangerous permissions
Dangerous permissions cover areas where the app wants data or resources that involve the user's
private information, or could potentially affect the user's stored data or the operation of other apps.
For example, the ability to read the user's contacts is a dangerous permission. If an app declares that
it needs a dangerous permission, the user has to explicitly grant the permission to the app. Until the
user approves the permission, your app cannot provide functionality that depends on that permission.
Special permissions
There are a couple of permissions that don't behave like normal and dangerous
permissions. SYSTEM_ALERT_WINDOW and WRITE_SETTINGS are particularly sensitive, so
most apps should not use them. If an app needs one of these permissions, it must declare the
permission in the manifest, and send an intent requesting the user's authorization. The system
responds to the intent by showing a detailed management screen to the user.
If the user Accepts the permissions, the app is installed. Else the app installation is cancelled.
2. Run-Time Permissions: If the Android 6 (API 23) or higher, the permission is requested at
the run time during the runnnig of the app.
If the user Accepts the permissions, then that feature of the app can be used. Else to use the feature,
the app requests the permission again. So, now the permissions are requested at runtime.
Content providers let you centralize content in one place and have many different
applications access it as needed.
A content provider behaves very much like a database where you can query it, edit its
content, as well as add or delete content using insert(), update(), delete(), and query()
methods.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
public class My Application extends ContentProvider
{
}
Fragments:
• A fragment runs in the context of an activity, but has its own life cycle and typically its own
user interface.
• Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse
of components in different layouts and their logic.
• As it is possible to dynamically add and remove fragments from an activity. The usage of
fragments allows designing very flexible user interfaces.
The Android Things Console provides easy and secure deployment of updates to your connected
devices. Google provides the infrastructure to host and deliver system and app updates with the
developer in final control.
Build factory images that contain OEM applications along with the system image
Push over-the-air (OTA) seamless updates, including OEM (original equipment manufacturer)
applications and the system image, to devices
To publish Android apps on Google Play, you'll need to create a Google Play Developer account.
Once you've selected an app, here are the pages you'll find in each category:
19. Write a program to create a text field and button “Navigate”. When you enter
www.google.com and press on navigate button it should open the google page.
activity_main.xml
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="60dp"
android:ems="10"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.575"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginLeft="156dp"
android:layout_marginTop="172dp"
android:text="Navigate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.implicit_intent_navigate;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
Button button;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editText = findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url=editText.getText().toString();
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
}
20. Write a program to display an image using imageview and a button named as change image.
Once you click on button another image should get displayed
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="249dp"
android:layout_weight="1"
android:src="@drawable/sun_spring_green_forest"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
MainActivity.java
package com.example.changeimage;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
Button button;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
img.setImageResource(R.drawable.palombaggia_beach_sunny);
}
});
}
}
SQLiteOpenHelper class
onCreate(SQLiteDatabase database) – is the method which is called first time when the database is
created and we need to use this method to create the tables and populate it as per the need.
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) – is the method called when
upgrade is done. We can drop the datbase and reset if required.
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.
There are many methods in SQLiteDatabase class. Some of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table
nullColumnHack, ContentValues values) specifies the table name, nullColumnHack
doesn't allow completely null values. If
second argument is null, android will store
null values if values are empty. The third
argument specifies the values to be stored.
int update(String table, ContentValues updates a row.
values, String whereClause, String[]
whereArgs)
Cursor query(String table, String[] returns a cursor over the resultset.
columns, String selection, String[]
selectionArgs, String groupBy, String
having, String orderBy)
Activity is one of the building blocks of Android OS. In simple words Activity is a screen that user
interact with. Every Activity in android has lifecycle like created, started, resumed, paused, stopped
or destroyed. These different states are known as Activity Lifecycle.
Short description of Activity Lifecycle example: (If 2 marks question with explanation)
onStart() – Called just after it’s creation or by restart method after onStop(). Here Activity start
becoming visible to user
onResume() – Called when Activity is visible to user and user can interact with it
onPause() – Called when Activity content is not visible because user resume previous activity
onStop() – Called when activity is not visible to user because some other activity takes place of it
onRestart() – Called when user comes on screen or resume the activity which was stopped
onCreate(Bundle savedInstanceState):
onCreate() method is called when activity gets memory in the OS. To use create state we need to
override onCreate(Bundle savedInstanceState) method. Bundle is a data repository object that
can store any kind of primitive data and this object will be null until some data isn’t saved in that.
onStart():
onStart() method is called just after it’s creation. In other case Activity can also be started by calling
restart method i.e after activity stop. So this means onStart() gets called by Android OS when
user switch between applications. For example, if a user was using Application A and then a
notification comes and user clicked on notification and moved to Application B, in this case
Application A will be paused. And again if a user again click on app icon of Application A then
Application A which was stopped will again gets started.
onResume():
Activity resumed is that situation when it is actually visible to user means the data displayed in the
activity is visible to user. In lifecycle it always gets called after activity start and in most use case
after activity paused (onPause).
onPause():
Activity is called paused when it’s content is not visible to user, in most case onPause() method
called by Android OS when user press Home button (Center Button on Device) to make hide.
Activity also gets paused before stop called in case user press the back navigation button. The
activity will go in paused state for these reasons also if a notification or some other dialog is
overlaying any part (top or bottom) of the activity (screen). Similarly, if the other screen or dialog is
transparent then user can see the screen but cannot interact with it. For example, if a call or
notification comes in, the user will get the opportunity to take the call or ignore it.
onStop():
Activity is called stopped when it’s not visible to user. Any activity gets stopped in case some other
activity takes place of it. For example, if a user was on screen 1 and click on some button and moves
to screen 2. In this case Activity displaying content for screen 1 will be stopped.
PT-2 QB CO6I prepared by Poonam V Page 24
Every activity gets stopped before destroy in case of when user press back navigation button. So
Activity will be in stopped state when hidden or replaced by other activities that have been launched
or switched by user. In this case application will not present anything useful to the user directly as
it’s going to stop.
onRestart():
Activity is called in restart state after stop state. So activity’s onRestart() function gets called when
user comes on screen or resume the activity which was stopped. In other words, when Operating
System starts the activity for the first time onRestart() never gets called. It gets called only in case
when activity is resumes after stopped state.
onDestroy():
Any activity is known as in destroyed state when it’s not in background. There can different cases at
what time activity get destroyed.
First is if user pressed the back navigation button then activity will be destroyed after completing the
lifecycle of pause and stop.
In case if user press the home button and app moves to background. User is not using it no more and
it’s being shown in recent apps list. So in this case if system required resources need to use
somewhere else then OS can destroy the Activity.
After the Activity is destroyed if user again click the app icon, in this case activity will be recreated
and follow the same lifecycle again.