100% found this document useful (2 votes)
572 views35 pages

2 Marks Questions:: A) List Features of Android Operating System

The document discusses several topics related to the Android operating system. It defines Android Virtual Devices (AVDs) as emulator configurations that allow developers to test applications by simulating real device capabilities. It also lists features of the Android OS such as being open source, supporting multi-tasking and widgets, and having extensive multimedia support. Additionally, it provides the directory structure for storing images during Android application development and defines the syntax for Intent filters.

Uploaded by

Mitalee Konde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
572 views35 pages

2 Marks Questions:: A) List Features of Android Operating System

The document discusses several topics related to the Android operating system. It defines Android Virtual Devices (AVDs) as emulator configurations that allow developers to test applications by simulating real device capabilities. It also lists features of the Android OS such as being open source, supporting multi-tasking and widgets, and having extensive multimedia support. Additionally, it provides the directory structure for storing images during Android application development and defines the syntax for Intent filters.

Uploaded by

Mitalee Konde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

2 marks Questions :

a) List features of Android Operating System.

Answer: The features of android operating system are as follows-:

1. Open Source -: The Android source is an open-source platform based on the


Linux kernel and multiple open-source
2. Multi-Platform Support -: In market, there are a wide range of hardware
devices powered by the android OS, including many different phones and
tablet.

• Multi-tasking -: Multi-tasking is available on virtually on all smartphones


platforms but hardly does any operating system do it better than

1. Widgets -: Widget is another thing that is working well on Android It has


worked so excellently, other operating systems and mobile app development.
2. Extensive Support -: It has an extensive support for multimedia hardware
control to perform playback or recording using camera and

b) Define Android Virtual Devices (AVD).

Answer: An Android Virtual Device (AVD) is an emulator configuration that allows


developers to test the application by simulating the real device capabilities. We can
configure the AVD by specifying the hardware and software options. AVD manager
enables an easy way of creating and managing the AVD with its graphical interface.
We can create as many AVDs as we need, based

on the types of device we want to test for. Below are the steps to create an AVD
from AVD manager graphical interface

1. Go to Window ->AVD Manager and select Virtual


2. Click on New to create a Virtual Device, give it some Name and select Target
Android Platform from the drop down list
3. Click “Create AVD” and we are done!

c) Write the directory path where images are stored while developing Android
application.
Answer: In Android Operating system, generally there are a lot of files inside the
directory structure. For example these are manifest file, java file, activity file and the
most important file is resource file. This is also shows as res file sometimes.

We stored our image in the resource file by following steps.

• First we need to download the image from our browser.


• Then we have to copy it from the folder in which the image is stored.
• Then after that we have to simple paste it in the resource
• If we want to put the icon or launcher icon then we have to paste the image in
the mipmap folder and select the shape and size.
d) List all attributes to develop a simple button.

• Answer: Basically in computer programming language, attributes are defined


as the characteristics to define a object or any element in the programming
language. You can also say this is the way to define the properties of the
element.
• The following attributes to develop a button in android studio are -:
• id: id is an attribute used to uniquely identify a text Button.
• gravity: The gravity attribute is an optional attribute which is used to control
the alignment of the text like left, right, center, top, bottom, center_vertical,
center_horizontal etc.
• text: text attribute is used to set the text in a Button. We can set the text in xml
as well as in the java
• textColor: textColor attribute is used to set the text color of a Button. Color
value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”
• textSize: textSize attribute is used to set the size of the text on Button. We can
set the text size in sp(scale independent pixel) or dp(density pixel).

e) Write the syntax for Intent-Filter tag.

Answer: An Android Intent is an abstract description of an operation to be


performed. It can be used with startActivity to launch an
Activity, broadcastIntent to send it to any interested BroadcastReceiver
components, and startService(Intent) or bindService(Intent, ServiceConnection,
int) to communicate with a background Service.

syntax:
<intent-filter android:icon=”drawable resource”
android:label=”string resource” android:priority=”integer” >
...
</intent-filter>

f) Define services in Android operating system.

Answer: 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 destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter


process communication (IPC).

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 component (like activity) 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. The client can unbind the service by calling
the unbindService() method.

4 marks Questions :
a) Describe the Android architecture in detail.

Answer: Android operating system is a stack of software components which is


roughly divided into five sections and four main layers as shown below in the
architecture diagram.

Linux kernel

At the bottom of the layers is Linux – Linux 3.6 with approximately 115 patches. This
provides a level of abstraction between the device hardware and it contains all the
essential hardware drivers like camera, keypad, display etc. Also, the kernel handles
all the things that Linux is really good at such as networking and a vast array of
device drivers, which take the pain out of interfacing to peripheral hardware.

Libraries

On top of Linux kernel there is a set of libraries including open-source Web browser
engine WebKit, well known library libc, SQLite database which is a useful repository
for storage and sharing of application data, libraries to play and record audio and
video, SSL libraries responsible for Internet security etc.

Android Runtime

This is the third section of the architecture and available on the second layer from
the bottom. This section provides a key component called Dalvik Virtual
Machine which is a kind of Java Virtual Machine specially designed and optimized
for Android.
The Dalvik VM makes use of Linux core features like memory management and
multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every
Android application to run in its own process, with its own instance of the Dalvik
virtual machine.

Application Framework

The Application Framework layer provides many higher-level services to applications


in the form of Java classes. Application developers are allowed to make use of these
services in their applications.

The Android framework includes the following key services −

• Activity Manager − Controls all aspects of the application lifecycle and


activity
• Content Providers − Allows applications to publish and share data with other
• Resource Manager − Provides access to non-code embedded resources such
as strings, color settings and user interface

• Notifications Manager − Allows applications to display alerts and


notifications to the
• View System − An extensible set of views used to create application user

Applications

You will find all the Android application at the top layer. You will write your
application to be installed on this layer only. Examples of such applications are
Contacts Books, Browser, Games etc.
b) Differentiate between JVM and DVM.

c) Explain the activity life cycle.

Answer: Android Activity Lifecycle is controlled by 7 methods of


android.app.Activity class. The android Activity is the subclass of
ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single
screen.
Let’s see the 7 lifecycle methods of android activity.

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.

d) Discuss the need of permissions in Android. Describe the permissions to set system
functionalities like bluetooth,camera.

Answer: Permission requests protect sensitive information available from a device


and should only be used when access to information is necessary for the functioning
of your app. This document provides tips on ways you might be able to achieve the
same (or better) functionality without requiring access to such information; it is not an
exhaustive discussion of how permissions work in the Android operating system.

For example, suppose your app needs to be able to take pictures with the device
camera. Your app can request the CAMERA permission, which allows your app to
access the camera directly. Your app would then use the camera APIs to control the
camera and take a picture. This approach gives your app full control over the
photography process, and lets you incorporate the camera UI into your app.

Requesting Camera Permissions for


Your App
If your app requires a dangerous permission, check whether your app has been
granted access for the operation that requires the permission:

if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)

!= PackageManager.PERMISSION_GRANTED) {

// Permission is not granted

Requesting Bluetooth Permissions for


Your App
In order to use Bluetooth features in your application, you must declare two
permissions. The first of these is BLUETOOTH. You need this permission to perform
any Bluetooth communication, such as requesting a connection, accepting a
connection, and transferring data.

<uses-permission android:name=”android.permission.BLUETOOTH” />

<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN” />


e) Explore the Steps to install and configure Android Studio and SDK.

Answer: As we know Android world is increasing day by day. Billions of Android apps
has been published on Google Play store. So it is the need of time that we should
learn some basics of Android development. Android Studio is an IDE (Integrated
Development Environment) for Android application development.

Features of Android Studio


Following are some interesting features of Android Studio:

• It provides a flexible Gradle-based build


• It also support C++ and NDK
• Run your app without building a new APK.
• Provides a virtual device to run and test your app

Installation
Step 1: Download android studio
Follow steps below for complete installation and configuration of Android Studio.

You can download Android Studio from this link or go


to developer.android.com homepage and search for downloads. Choose appropriate
platform either for windows, mac or linux. Following are the pre requirements for
windows operating system.

Step 2 :Run Exe File


Now the next step is to launch .exe file you just download. Following screen will
appear

Click next and select Android SDK checked if you don’t have it already. Better is to
leave the default settings.

Make sure Android virtual device is also checked.

step 3: Choose components


Next step is to accept license and agreement. Click on I Agree

Step 4: Accept license


Next step is to set location of installation. Please make sure your disk has minimum
required space before clicking on Next. For Android Studio installation location must
have at least 500MB free space. For Android SDK installation, selected location
must have at least 3.25GB free space.
Step 5: Install location
Next step is to choose the start menu folder, where you want to create shortcut. If
you don’t want to create a shortcut just mark Do not create shortcut.

Step 6: Choose start menu folder And


hit Install button.
It will start installation.

Step 7: Finish
This informs you installation has completed. Click Finish. Make sure Start Android
Studio is checked. Following splash screen of Android Studio will appear.

f) Explain Date and Time picker with its methods.


Answer: Android Date Picker allows you to select the date consisting of day, month
and year in your custom user interface. For this functionality android provides
DatePicker and DatePickerDialog components.

Apart form date attributes, DatePicker object is also passed into this function. You
can use the following methods of the DatePicker to perform further operation.

Sr.No Method & description


getDayOfMonth()

1
This method gets the selected day of month
getMonth()

2
This method gets the selected month
getYear()

3
This method gets the selected year
setMaxDate(long maxDate)

4
This method sets the maximal date supported by this DatePicker in milliseconds
since January 1, 1970 00:00:00 in getDefault() time zone

setMinDate(long minDate)
5

This method sets the minimal date supported by this NumberPicker in milliseconds
since January 1, 1970 00:00:00 in getDefault() time zone
setSpinnersShown(boolean shown)

6
This method sets whether the spinners are shown
updateDate(int year, int month, int dayOfMonth)

7
This method updates the current date
getCalendarView()

8
This method returns calendar view
getFirstDayOfWeek()

9
This Method returns first day of the week
Android Time Picker allows you to select the time of day in either 24 hour or
AM/PM mode. The time consists of hours, minutes and clock format. Android
provides this functionality through TimePicker class.

<TimePicker android:id=”@+id/timePicker1″ android:layout_width=”wrap_content”

android:layout_height=”wrap_content” />

is24HourView()

1
This method returns true if this is in 24 hour view else false
isEnabled()

2
This method returns the enabled status for this view
setCurrentHour(Integer currentHour)
3
This method sets the current hour
setCurrentMinute(Integer currentMinute)

4
This method sets the current minute
setEnabled(boolean enabled)

5
This method set the enabled state of this view

setIs24HourView(Boolean is24HourView)

6
This method set whether in 24 hour or AM/PM mode
setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedL
istener)

7
This method Set the callback that indicates the time has been adjusted by the user

g) Describe the significance of SQLite database in Anroid.

Answer: SQLite is an open-source relational database i.e. used to perform


database operations on android devices such as storing, manipulating or retrieving
persistent data from the database.

It is embedded in android bydefault. So, there is no need to perform any database


setup or administration task.

Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the
next page.

Database Creation
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.Its syntax is given below

SQLiteDatabase mydatabase = openOrCreateDatabase(“your


database name”,MODE_PRIVATE,null);

Apart from this , there are other functions available in the database package , that
does this job. They are listed below

Sr.No Method & Description


openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,
DatabaseErrorHandler errorHandler)

1 This method only opens the existing database with the appropriate flag mode. The
common flags mode could be OPEN_READWRITE OPEN_READONLY

openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)

2
It is similar to the above method as it also opens the existing database but it does not
define any handler to handle the errors of databases
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)

3
It not only opens but create the database if it not exists. This method is equivalent to
openDatabase method.
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)

4
This method is similar to above method but it takes the File object as a path rather then
a string. It is equivalent to file.getPath()
h) Observe the following GUI and write an XML file using relative layout to create
the same.

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” androi


d:layout_width=”fill_parent”

android:layout_height=”fill_parent” android:paddingLeft=”16dp”
android:paddingRight=”16dp” >

<EditText

android:id=”@+id/name” android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:hint=”@string/reminder” />

<LinearLayout android:orientation=”vertical” android:layout_width=”fill_parent”


android:layout_height=”fill_parent” android:layout_alignParentStart=”true”
android:layout_below=”@+id/name” android:orientation=”horizontal”>

<EditText

android:id=”@+id/name” android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:hint=”@string/reminder” />

<EditText

android:id=”@+id/name” android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:hint=”@string/reminder” />

</LinearLayout>

<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content”


android:text=”New Button” android:id=”@+id/button” /
</RelativeLayout>

i) Write a program to display circular progress bar.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all
required details to create a new project.

Step 2 − Add the following code to res/drawable/circular_progress_bar.xml.

<? xml version= “1.0” encoding= “utf-8” ?>

<rotate xmlns: android = “http://schemas.android.com/apk/res/android” android


:fromDegrees= “270”

android :toDegrees= “270” >

<shape

android :innerRadiusRatio= “2.5” android :shape= “ring”

android :thickness= “1dp”

android :useLevel= “true” > <!– this line fixes the issue for lollipop api 21 –>

<gradient

android :angle= “0”

android :endColor= “#007DD6” android :startColor= “#007DD6” android :type=


“sweep”

android :useLevel= “false” />

</shape>

</rotate>

Step 3 − Add the following code to res/drawable/circular_shape.xml

<? xml version= “1.0” encoding= “utf-8” ?>

<shape xmlns: android = “http://schemas.android.com/apk/res/android” android


:innerRadiusRatio= “2.5”

android :shape= “ring” android :thickness= “1dp” android :useLevel= “false” >
<solid android :color= “#CCC” />

</shape>

Step 4 − Add the following code to res/layout/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” android :layout_margin= “16dp”

tools :context= “.MainActivity” >

<ProgressBar

android :id= “@+id/progressBar”

style= “?android:attr/progressBarStyleHorizontal” android :layout_width= “200dp”

android :layout_height= “200dp” android :layout_centerInParent= “true”

android :background= “@drawable/circular_shape” android :indeterminate= “false”

android :max= “100”

android :progress= “65”

android :progressDrawable= “@drawable/circular_progress_bar” />

</RelativeLayout>

Step 5 − Add the following code to src/MainActivity.java


package app.tutorialspoint.com.sample ;

import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ;

public class MainActivity extends AppCompatActivity { @Override

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


setContentView(R.layout. activity_main ) ;

Step 6 − Add the following code to androidManifest.xml

<? xml version= “1.0” encoding= “utf-8” ?>

<manifest xmlns: android = “http://schemas.android.com/apk/res/android” package=


“app.tutorialspoint.com.sample” >

<uses-permission android :name= “android.permission.CALL_PHONE” />

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

d) Explain zoom control (IN / OUT) with the help of an example.

Answer: In Android, Zoom Controls class display simple set of controls that is used
for zooming and provides callback to register for events. Zoom Controls has two
buttons ZoomIn and ZoomOut which are used to control the zooming functionality.

Zoom Controls code in XML:


<ZoomControls android:id=”@+id/simpleZoomControl”
android:layout_width=”wrap_content”

android:layout_height=”wrap_content” />
Important Methods Of Zoom Controls:

Now let’s discuss some common methods which are used to configure
ZoomControls in our application.

This method is used to hide the ZoomControls from the screen. In some
1. hide():
cases we need to hide the ZoomControls from the screen so that we use this
function.
This method is used to show the ZoomControls which we hide from the
2. show():
screen by using hide method.
This example demonstrates how do I
Zoom In and Zoom Out an android
ImageView.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all
required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.a
ndroid.com/tools”

android:layout_width=”match_parent” android:layout_height=”match_parent”
android:orientation=”vertical” android:padding=”16dp” android:gravity=”center”
tools:context=”.MainActivity”>

<ImageView android:id=”@+id/imageView” android:layout_width=”match_parent”

android:layout_height=”match_parent” android:src=”@drawable/image” />

</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java

import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;

import android.view.MotionEvent;

import android.view.ScaleGestureDetector; import android.widget.ImageView;

public class MainActivity extends AppCompatActivity { private ScaleGestureDetector


scaleGestureDetector; private float mScaleFactor = 1.0f;

private ImageView imageView; @Override

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


setContentView(R.layout.activity_main); imageView=findViewById(R.id.imageView);
scaleGestureDetector = new ScaleGestureDetector(this, new

ScaleListener());

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
scaleGestureDetector.onTouchEvent(motionEvent); return true;

private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

@Override

public boolean onScale(ScaleGestureDetector scaleGestureDetector) { mScaleFactor *=


scaleGestureDetector.getScaleFactor(); mScaleFactor = Math.max(0.1f,
Math.min(mScaleFactor, 10.0f)); imageView.setScaleX(mScaleFactor);
imageView.setScaleY(mScaleFactor);

return true;

}
Step 4 − Add the following code to androidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>

<manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”app.com.


sample”>

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

k) Develop an application to send and receive SMS. (Write ONLY .java and permission tag
in manifest file)

Answers: In Android, you can use SmsManager API or devices Built-in SMS
application to send SMS’s. In this tutorial, we shows you two basic examples to send
SMS message –

SmsManager API
SmsManager smsManager = SmsManager.getDefault();

smsManager.sendTextMessage(“phoneNo”, null, “sms message”, null, null);


Built-in SMS application

Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra(“sms_body”,


“default content”); sendIntent.setType(“vnd.android-dir/mms-sms”);

startActivity(sendIntent);

Of course, both need SEND_SMS permission.

<uses-permission android:name=”android.permission.SEND_SMS” />

Following is the content of the


modified main activity file
src/com.example.tutorialspoint/MainActivity.java. package com.example.tutorialspoint;

import android.Manifest;

import android.content.pm.PackageManager; import android.os.Bundle;

import android.app.Activity;

import android.support.v4.app.ActivityCompat; import


android.support.v4.content.ContextCompat; import android.telephony.SmsManager;

import android.util.Log;
import android.view.Menu; import android.view.View;

import android.widget.Button; import android.widget.EditText; import android.widget.Toast;

public class MainActivity extends Activity {

private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ; Button sendBtn;

EditText txtphoneNo; EditText txtMessage; String phoneNo; String message;

@Override

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


setContentView(R.layout.activity_main);

sendBtn = (Button) findViewById(R.id.btnSendSMS); txtphoneNo = (EditText)


findViewById(R.id.editText); txtMessage = (EditText) findViewById(R.id.editText2);

sendBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view)


{

sendSMSMessage();

});

protected void sendSMSMessage() { phoneNo = txtphoneNo.getText().toString(); message =


txtMessage.getText().toString();

if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)

!= PackageManager.PERMISSION_GRANTED) {

if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else { ActivityCompat.requestPermissions(this,

new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);

@Override

public void onRequestPermissionsResult(int requestCode,String permissions[], int[]


grantResults) {

switch (requestCode) {

case MY_PERMISSIONS_REQUEST_SEND_SMS: {

if (grantResults.length > 0

&& grantResults[0] == PackageManager.PERMISSION_GRANTED) { SmsManager


smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null,
message, null, null); Toast.makeText(getApplicationContext(), “SMS sent.”,

Toast.LENGTH_LONG).show();

} else { Toast.makeText(getApplicationContext(),

“SMS faild, please try again.”, Toast.LENGTH_LONG).show(); return;

Following is the default content of AndroidManifest.xml –


<?xml version=”1.0″ encoding=”utf-8″?>

<manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.exa


mple.tutorialspoint” >

<uses-permission android:name=”android.permission.SEND_SMS” />

<application android:allowBackup=”true” android:icon=”@drawable/ic_launcher”


android:label=”@string/app_name” android:theme=”@style/AppTheme” >

<activity

android:name=”com.example.tutorialspoint.MainActivity”
android:label=”@string/app_name” >

<intent-filter>

<action android:name=”android.intent.action.MAIN” />

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

</intent-filter>

</activity>

</application>

</manifest>
6 marks Questions :

a) Develop the registration form using the following GUI.

<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”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.android_examples.com.edittextimageadd.MainActivity” >

<FrameLayout>

<ImageView

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:src=”@drawable/banner_image”
android:contentDescription=”@string/my_image_description”

/>
>

</FrameLayout>

<EditText android:id=”@+id/editText1″ android:hint=”Enter your name”


android:layout_width=”wrap_content” android:layout_height=”wrap_content”

android:layout_centerHorizontal=”true” android:layout_centerVertical=”true”
android:ems=”10″ android:drawableLeft=”@drawable/name_image” >

<requestFocus />

</EditText>

<EditText android:id=”@+id/editText1″ android:hint=”Enter your email”


android:layout_width=”wrap_content” android:layout_height=”wrap_content”

android:layout_centerHorizontal=”true” android:layout_centerVertical=”true”
android:ems=”10″ android:drawableLeft=”@drawable/email_image” >

<requestFocus />

</EditText>

<EditText android:id=”@+id/editText1″ android:hint=”Enter your password”


android:layout_width=”wrap_content”

android:layout_height=”wrap_content” android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:ems=”10″ android:drawableLeft=”@drawable/pass_image” >

<requestFocus />

</EditText>

<EditText android:id=”@+id/editText1″ android:hint=”confirm password”


android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:ems=”10″ android:drawableLeft=”@drawable/conpass_image” >

<requestFocus />

</EditText>

<EditText android:id=”@+id/editText1″

android:hint=”Enter your mobile” android:layout_width=”wrap_content”


android:layout_height=”wrap_content” android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:ems=”10″ android:drawableLeft=”@drawable/mobile_image” >

<requestFocus />

</EditText>

<RadioButton

android:id=”@+id/radioMale” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”male” android:checked=”true” />

<RadioButton

android:id=”@+id/radioFemale” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”female” />

<Button

android:id=”@+id/btnDisplay” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”register” />
</RelativeLayout>

b) Write a program to capture an image using camera and display it.

Answer: Here’s an example activity that will launch the camera app and then retrieve
the image and display it.

package edu.gvsu.cis.masl.camerademo;

import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap;


import android.os.Bundle; import android.view.View; import android.widget.Button;

import android.widget.ImageView;

public class MyCameraActivity extends Activity

private static final int CAMERA_REQUEST = 1888; private ImageView imageView;

private static final int MY_CAMERA_PERMISSION_CODE = 100;

@Override

public void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState); setContentView(R.layout.main);

this.imageView = (ImageView)this.findViewById(R.id.imageView1); Button photoButton =


(Button) this.findViewById(R.id.button1); photoButton.setOnClickListener(new
View.OnClickListener()

@Override

public void onClick(View v)

{
if (checkSelfPermission(Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED)

requestPermissions(new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);

else

Intent cameraIntent = new


Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(cameraIntent, CAMERA_REQUEST);

});

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,


@NonNull int[] grantResults)

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == MY_CAMERA_PERMISSION_CODE)

if (grantResults[0] == PackageManager.PERMISSION_GRANTED)

Toast.makeText(this, “camera permission granted”, Toast.LENGTH_LONG).show();


Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(cameraIntent, CAMERA_REQUEST);

else

Toast.makeText(this, “camera permission denied”, Toast.LENGTH_LONG).show();

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)

if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)

Bitmap photo = (Bitmap) data.getExtras().get(“data”); imageView.setImageBitmap(photo);

}
Here is the layout that the above activity uses. It is simply a LinearLayout containing
a Button with id button1 and an ImageView with id imageview1:

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orienta


tion=”vertical”

android:layout_width=”fill_parent” android:layout_height=”fill_parent”

>
<Button android:id=”@+id/button1″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”@string/photo”></Button>

<ImageView android:id=”@+id/imageView1″ android:layout_height=”wrap_content”


android:src=”@drawable/icon” android:layout_width=”wrap_content”></ImageView>

</LinearLayout>

And one final detail, be sure to add:

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

c) Develop a program to send an email

Answers:

package com.example.sendemail; import android.os.Bundle;

import android.app.Activity; import android.content.Intent; import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener; import android.widget.Button;

import android.widget.EditText;

public class MainActivity extends Activity {

EditText editTextTo,editTextSubject,editTextMessage; Button send;

@Override

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


setContentView(R.layout.activity_main);

editTextTo=(EditText)findViewById(R.id.editText1);
editTextSubject=(EditText)findViewById(R.id.editText2);
editTextMessage=(EditText)findViewById(R.id.editText3);

send=(Button)findViewById(R.id.button1);
send.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View arg0) {

String to=editTextTo.getText().toString();

String subject=editTextSubject.getText().toString();

String message=editTextMessage.getText().toString();

Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_EMAIL,


new String[]{ to}); email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);

//need this to prompts email client only email.setType(“message/rfc822”);

startActivity(Intent.createChooser(email, “Choose an Email client :”));

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);

return true; } }

For XML file , simple add all the


required edit text and button and set
the id as per the above code.
d) Write a program to locate user’s current location. (Write ONLY .java and manifest file)

Answer: There are two ways to get a users location in our application:

• location.LocationListener : This is a part of the Android API.


• google.android.gms.location.LocationListener : This is present in the Google
Play Services API. (We’ll look into this in the next tutorial)

Android Location Services is available since Android A


PI 1.

Google officially recommends using Google Play Location Service APIs. Android
Location Services API is still used to develop location-based apps for devices that
don’t support Google Play Services.

XML File
<?xml version=”1.0″ encoding=”utf-8″?>

<RelativeLayout
xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.a
ndroid.com/tools” android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.currentlocation.MainActivity”>

<Button

android:layout_width=”match_parent” android:layout_height=”wrap_content”
android:text=”Get Current Location” android:id=”@+id/getLocationBtn”/>

<TextView android:layout_width=”wrap_content”

android:layout_height=”wrap_content” android:id=”@+id/locationText”
android:layout_below=”@id/getLocationBtn”/>

</RelativeLayout>
Manifest File

<?xml version=”1.0″ encoding=”utf-8″?>


<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.currentlocation”>

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

<uses-permission android:name=”android.permission.INTERNET” />

<application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher”


android:label=”@string/app_name” 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

package com.currentlocation;

import android.content.Context; import android.location.Location;

import android.location.LocationListener; import android.location.LocationManager;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;

import android.view.View; import android.widget.Button; import android.widget.TextView;


import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener {


Button getLocationBtn;
TextView locationText; LocationManager locationManager;

@Override

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


setContentView(R.layout.activity_main);

getLocationBtn = (Button)findViewById(R.id.getLocationBtn); locationText =


(TextView)findViewById(R.id.locationText);

getLocationBtn.setOnClickListener(new View.OnClickListener() { @Override

public void onClick(View v) { getLocation();

});

void getLocation() { try {

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,

5, this);

catch(SecurityException e) { e.printStackTrace();

@Override

public void onLocationChanged(Location location) { locationText.setText(“Current


Location: ” + location.getLatitude() + “, ” +

location.getLongitude());

@Override

public void onProviderDisabled(String provider) { Toast.makeText(MainActivity.this,


“Please Enable GPS and Internet”,
Toast.LENGTH_SHORT).show();

@Override

public void onStatusChanged(String provider, int status, Bundle extras) {

@Override

public void onProviderEnabled(String provider) {

You might also like