0% found this document useful (0 votes)
82 views28 pages

5-6 Chapter QSTN Answer

This document provides a summary of important questions and answers related to the Mobile Application Development (MAD) course. It includes multiple choice and descriptive questions covering topics like handling databases in Android, the activity and service lifecycles, location data, developing an Android application, intents, sensors, animations, text-to-speech, Google Maps, geocoding, and SMS classes. Definitions and examples are provided for key concepts like content providers and fragments.
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
0% found this document useful (0 votes)
82 views28 pages

5-6 Chapter QSTN Answer

This document provides a summary of important questions and answers related to the Mobile Application Development (MAD) course. It includes multiple choice and descriptive questions covering topics like handling databases in Android, the activity and service lifecycles, location data, developing an Android application, intents, sensors, animations, text-to-speech, Google Maps, geocoding, and SMS classes. Definitions and examples are provided for key concepts like content providers and fragments.
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/ 28

STUDY SHADES..

M.M. Polytechnic, Thergaon


Important Questions and Answers on Unit 5 and Unit 6

Course: Mobile Application Development (MAD) Course Code: 22617


Program: CO/IF-6I Semester: VI
-----------------------------------------------------------------------------------------------
2 Marks

1. Enlist different ways to handle databases in android? Elaborate any one.


There are many ways to store your data, such as in an online database, in a local SQLite
database, or even in a text file.
SQLite: It is a opensource SQL database that stores data to a text file on a device. Android
comes in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you
don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

2. What Is Activity in android?


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.

3. Draw the life cycle of an activity.

4. Name any 4 methods to get location data in android.

Computer Engineering Department


STUDY SHADES.....
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.

5. Write steps to develop an android application.


Step 1: Start with Android Studio
Step 2: Installation of Java Development Kit (JDK)
Step 3: Start Your Project
Step 4: Select Activity
Step 5: Selecting the Layout
Step 6: Edit the Welcome Message
Step 7: Adding Button to your Activity
Step 8: Test your App

6. Write the syntax for Intent-Filter tag.


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

7. Define services in Android operating system.

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
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).

8. Enlist the steps to publish the Android application.


Step 1: Sign up. Sign up for an account on the Android Developer Console. ...
Step 2: Create a new application. ...
Step 3: Prepare multimedia. ...
Step 4: Prepare code for release. ...
Step 5: Build a release-ready APK. ...
Step 6: Upload APK. ...
Complete the checklist on the left until all the items have a green checkmark.
9. What is an Intent? Enlist its Types.
Intent is to perform an action. It is mostly used to start activity, send broadcast receiver, start
services and send message between two activities.
Types of intents are: Implicit Intents and Explicit Intents.

10. What Is Service in android? Enlist its Types.


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 User Interface.
Types of services:
Foreground
A foreground service performs some operation that is noticeable to the user. For example, an
audio app would use a foreground service to play an audio track.

Background
A background service performs an operation that isn't directly noticed by the user. For
example, if an app used a service to compact its storage, that would usually be a background
service.

Bound
A service is bound when an application component binds to it by calling bindService(). A
bound service offers a client-server interface that allows components to interact with the
service, send requests, receive results, and even do so across processes with interprocess
communication (IPC).

11. What Is Sensor in android? Enlist its Types.


Sensors can be used to monitor the three-dimensional device movement i.e. motion,
orientation or change in the environment of the device. 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.

The Android platform supports three broad categories of sensors:

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
1) Motion Sensors : These are used to measure acceleration forces and rotational forces along
with three axes.

2) Position Sensors: These are used to measure the physical position of device.

3) Environmental Sensors: These are used to measure the environmental changes such as
temperature, humidity etc.

12. What is Animation? Enlist its Types.


Animations can add visual cues that notify users about what's going on in your app. They are
especially useful when the UI changes state, such as when new content loads or new actions
become available. Animations also add a polished look to your app, which gives it a higher
quality look and feel.

There’s three main types of animations available on Android: ViewAnimation, Property


Animation, DrawableAnimation and much more.

13. What is TTS feature of Android?


Text to speech (TTS) makes an android device read the text and convert it to audio out via the
speaker. Android TTS supports multiple languages. TTS is a simple but powerful feature. It can
also be effectively used in mobile APPs dedicated to visually impaired people or in educational
app for kids or can be used in pronunciation learning app, etc. These are some of the ways
you can use TTS. Using TextToSpeech enhances interaction between the user and the mobile
application.

14. Explain Google Map with types.

Android provides facility to integrate Google map in our application. Google map displays
your current location, navigate location direction, search location etc. We can also
customize Google map according to our requirement.

Types of Google Maps

There are four different types of Google maps, as well as an optional to no map at all. Each
of them gives different view on map. These maps are as follow:

1. Normal: This type of map displays typical road map, natural features like river and some
features build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical road maps. It also
displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display road and
feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour lines and
labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
15. Explain Geocoding & Reverse Geocoding.

Geocoding is the process of converting addresses (like a street address) into geographic
coordinates (like latitude and longitude), which you can use to place markers on a map, or
position the map.

Reverse geocoding is the process of converting geographic coordinates into a human-


readable address.

16. List various classes of SMS Telephony.

1. Telephony.Sms.Conversations
Contains a view of SMS conversations (also referred to as threads).

2. Telephony.Sms.Draft
Contains all draft text-based SMS messages in the SMS app.

3. Telephony.Sms.Inbox
Contains all text-based SMS messages in the SMS app inbox.

4. Telephony.Sms.Intents
Contains constants for SMS related Intents that are broadcast.

5. Telephony.Sms.Outbox
Contains all pending outgoing text-based SMS messages.

6. Telephony.Sms.Sent
Contains all sent text-based SMS messages in the SMS app.

4 Marks

1. Define content provider and explain fragments.

A Content Provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. A content provider can use
different ways to store its data and the data can be stored in files, in a database or even over
a network. Content Providers support the four basic operations, normally called CRUD-
operations. CRUD is the acronym for create, read, update and delete.

A fragment is an independent Android component which can be used by an activity. A


fragment encapsulates functionality so that it is easier to reuse within activities and layouts. A
fragment runs in the context of an activity, but has its own life cycle and typically its own user
interface. It is also possible to define fragments without an user interface, i.e., headless
fragments.

2. Describe types of permissions used while developing android applications.


Types of Permissions:

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the permission is
requested at the installation time at the Google Play Store. 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 running 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.
Permission to:
Access sensitive user information
Optional hardware features
Activity permission
Service permission
Broadcast permission
Content Provider permission
URI permissions
Normal permissions
Signature permissions
Dangerous permissions

3. Explain the activity life cycle.


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

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

4. Discuss the need of permissions in Android. Describe the permissions to set system
functionalities like Bluetooth, camera.
The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as certain
system features (such as camera and internet).

permissions to set system Bluetooth


<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

permissions to set system camera


Camera Features - Your application must also declare use of camera features, for example:
<uses-feature android:name="android.hardware.camera" />
Storage Permission - If your application saves images or videos to the device's external
storage (SD Card), you must also specify this in the manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Audio Recording Permission - For recording audio with video capture, your application must
request the audio capture permission.
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

Location Permission - If your application tags images with GPS location information, you must
request the ACCESS_FINE_LOCATION permission.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

5. Describe the significance of SQLite database in Android.


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 by default. So, there is no need to perform any database setup or
administration task. SQLiteDatabase has methods to create, delete, execute SQL commands,
and perform other common database management tasks.

The android.database.sqlite.SQLiteOpenHelper class is used for database creation and


version management. For performing any database operation, you have to provide the
implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

6. Discuss Developer console with its purpose.

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.

Using the console, developers and device makers can:

• Download and install the latest Android Things system image


• Build factory images that contain OEM applications along with the system image
• Push over-the-air (OTA) seamless updates, including OEM applications and the system image,
to devices
• Manage and share OEM applications across products and owners
• Monitor informative analytics to understand how well products are performing

7. List sensors in Android and explain any one in detail.

The Android platform supports three broad categories of sensors:

• Motion sensors

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
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.

Android Sensors Types

• Photometer is used to sense and control the brightness. Besides, there are sensors for
pressure, humidity, and temperature.
• For movements, Accelerometer is used to detect shakes/tilt gestures.
• Proximity Sensors are used to detect how close the object is to the device. It’s commonly
present in Call Applications. As you bring the phone close to the ear, the screen goes black,
thanks to this sensor. Though the maximum range of proximity is 5 cms.
• Gyroscope is used to measure rotation/spin. Gravity sensors are used to measure the force
of gravity.
• Magneto Meter is used to get the device position.
• Pedometer is used to detect the number of steps the user takes.

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


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.
Important Methods of Zoom Controls:

1. hide(): This method is used to hide the ZoomControls from the screen. In some cases we
need to hide the ZoomControls from the screen so that we use this function.
2. show(): This method is used to show the ZoomControls which we hide from the screen by
using hide method.
3. setOnZoomInClickListener(OnClickListenerlistener): This is a listener event automatically
called when we click on the Zoom In button of ZoomControls. In this listener we add the code
to zoom in image.
4. setOnZoomOutClickListener(OnClickListenerlistener): This is a listener event
automatically called when we click on the Zoom Out button of ZoomControls. In this listener
we add the code for zoom out a image.
5. setIsZoomInEnabled(boolean isEnabled): This method is used to enable or disable the
zoom In button of ZoomControls. In this method we set a Boolean value either true or false.
By default it has true value but sometime after a limit of zoom in we need to disable the zoom
in functionality i.e. after that we didn’t need more zoom in.

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
6. setIsZoomOutEnabled(boolean isEnabled): This method is used to enable or disable the
zoom Out button of ZoomControls. In this method we set a Boolean value means true or false.
By default it has true value but sometime after a limit of zoom out we need to disable the
zoom out functionality means at that time we didn’t need more zoom out.
<ZoomControls
android:id="@+id/simpleZoomControl"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

9. Draw Android System Architecture?

10. Explain with Diagram Service Life Cycle?

There can be two forms of a service. The lifecycle of service can follow two different paths: started or 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. The service cannot be stopped until all clients unbind the
service.

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

Like any other components service also has callback methods. These will be invoked while
the service is running to inform the application of its state.

onCreate()
This is the first callback which will be invoked when any component starts the service. If the
same service is called again while it is still running this method wont be invoked. Ideally one
time setup and intializing should be done in this callback.

onStartCommand()
This callback is invoked when service is started by any component by calling startService(). It
basically indicates that the service has started and can now run indefinetly.

onBind()
This is invoked when any component starts the service by calling onBind.

onUnbind()
This is invoked when all the clients are disconnected from the service.

onRebind()
This is invoked when new clients are connected to the service. It is called after onUnbind

onDestroy()
This is a final clean up call from the system. This is invoked just before the service is being
destroyed. Could be very useful to cleanup any resources such as threads, registered
listeners, or receivers.

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
11. What is Fragment? Explain with example.
Fragment is a part of an activity which enables more modular activity design. It will not be
wrong if we say a fragment is a kind of sub-activity. It represents behaviour or a portion of
user interface in an Activity.

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="fill_parent"
android:layout_height="fill_parent"
tools:context="example.javatpoint.com.fragmentexample.MainActivity">

<fragment
android:id="@+id/fragment1"
android:name="example.javatpoint.com.fragmentexample.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>

<fragment
android:id="@+id/fragment2"
android:name="example.javatpoint.com.fragmentexample.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>

</LinearLayout>

12. How to play Audio & Video in Android?


To play Audio & Video in Android the multimedia framework is used. The Android multimedia
framework includes support for playing variety of common media types, so that you can easily
integrate audio, video and images into your applications. You can play audio or video from
media files stored in your application's resources (raw resources), from standalone files in the
file system, or from a data stream arriving over a network connection, all
using MediaPlayer APIs.

The following classes are used to play sound and video in the Android framework:

MediaPlayer

This class is the primary API for playing sound and video. An object of this class can fetch,
decode, and play both audio and video with minimal setup. It supports several different
media sources such as:

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
• Local resources
• Internal URIs, such as one you might obtain from a Content Resolver
• External URLs (streaming)

AudioManager

This class manages audio sources and audio output on a device.

For example,

Uri myUri = ....; // initialize Uri here


MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();

13. Explain how to Create & Connect SQLite?


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 db;
db=openOrCreateDatabase(String path, int mode, SQLiteDatabase.CursorFactory factory) ;

This method is used to create/open database. As the name suggests, it will open a database
connection if it is already there, otherwise, it will create a new one.
Arguments:
String path: Name of the database
Int mode: operating mode. Use 0 or "MODE_PRIVATE" for the default operation, or
"CREATE_IF_NECESSARY" if you like to give an option that "if a database is not there, create
it"
CursorFactory factory: An optional factory class that is called to instantiate a cursor when a
query is called

Example,

db=openOrCreateDatabase("XYZ_Database",SQLiteDatabase.CREATE_IF_NECESSARY,null);

14. What is Transaction? Explain with example.


Transactions are units or sequences of work accomplished in a logical order, whether in a
manual fashion by a user or automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you
are creating, updating, or deleting a record from the table, then you are performing
transaction on the table. It is important to control transactions to ensure data integrity and
to handle database errors.

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

For Example,

BEGIN TRANSACTION;

UPDATE accounts
SET balance = balance - 1000
WHERE account_no = 100;

UPDATE accounts
SET balance = balance + 1000
WHERE account_no = 200;

INSERT INTO account_changes(account_no,flag,amount,changed_at)


VALUES(100,'-',1000,datetime('now'));

INSERT INTO account_changes(account_no,flag,amount,changed_at)


VALUES(200,'+',1000,datetime('now'));

COMMIT;

15. Describe location based services. List important methods.


Location Based Services are provided by Android through its location framework. The
framework provides a location API which consists of certain classes and interface. These
classes and interface are the key components which allow us to develop Location Based
Application in Android.

Classes and Interfaces of Location Based Services:

LocationManager – This class helps to get access to the location service of the system.
LocationListener – This interface acts as the listener which receives notification from the
location manager when the location changes or the location provider is disabled or enabled.
Location – This is the class which represents the geographic location returned at a particular
time.

Methods:

1 abstract void onConnected(Bundle connectionHint)


This callback method is called when location service is connected to the location client
successfully. You will use connect() method to connect to the location client.
2 abstract void onDisconnected()
This callback method is called when the client is disconnected. You will use disconnect() method
to disconnect from the location client.
3 abstract void onConnectionFailed(ConnectionResult result)
This callback method is called when there was an error connecting the client to the service.
4 abstract void onLocationChanged(Location location)
This callback method is used for receiving notifications from the LocationClient when the location
has changed.

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

16. Develop an application to send SMS. (Write ONLY .java and permission tag in manifest file)
***to answer this question write only the code which is in bold style***
Send SMS

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javapapers.androidsms">

<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=".SendSmsActivity"
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>

activity_sms.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/toPhoneNumberTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number" />

<EditText
android:id="@+id/toPhoneNumberET"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"/>

<TextView
android:id="@+id/smsMessageTV"
android:layout_width="wrap_content"

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
android:layout_height="wrap_content"
android:text="SMS Message" />

<EditText
android:id="@+id/smsMessageET"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"/>

<Button android:id="@+id/sendSMSBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send SMS"/>

</LinearLayout>

SendSmsActivity.java
package com.javapapers.androidsms;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSmsActivity extends Activity {

Button sendSMSBtn;
EditText toPhoneNumberET;
EditText smsMessageET;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
sendSMSBtn = (Button) findViewById(R.id.sendSMSBtn);
toPhoneNumberET = (EditText) findViewById(R.id.toPhoneNumberET);
smsMessageET = (EditText) findViewById(R.id.smsMessageET);
sendSMSBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMS();
}
});
}

protected void sendSMS() {


String toPhoneNumber = toPhoneNumberET.getText().toString();

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
String smsMessage = smsMessageET.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(toPhoneNumber, null, smsMessage, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Sending SMS failed.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}

Receive SMS
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javapapers.androidreceivesms" >
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".SmsActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>

<receiver android:name=".SmsBroadcastReceiver" android:exported="true" >


<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

</application>

</manifest>

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

SmsBroadcastReceiver.java

package com.javapapers.androidreceivesms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsBroadcastReceiver extends BroadcastReceiver {

public static final String SMS_BUNDLE = "pdus";

public void onReceive(Context context, Intent intent) {


Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

String smsBody = smsMessage.getMessageBody().toString();


String address = smsMessage.getOriginatingAddress();

smsMessageStr += "SMS From: " + address + "\n";


smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

//this will update the UI with message


SmsActivity inst = SmsActivity.instance();
inst.updateList(smsMessageStr);
}
}
}

SmsActivity.java

package com.javapapers.androidreceivesms;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class SmsActivity extends Activity implements OnItemClickListener {

private static SmsActivity inst;


ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;

public static SmsActivity instance() {


return inst;
}

@Override
public void onStart() {
super.onStart();
inst = this;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
smsListView = (ListView) findViewById(R.id.SMSList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);

refreshSmsInbox();
}

public void refreshSmsInbox() {


ContentResolver contentResolver = getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null,
null, null, null);
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
"\n" + smsInboxCursor.getString(indexBody) + "\n";

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
arrayAdapter.add(str);
} while (smsInboxCursor.moveToNext());
}

public void updateList(final String smsMessage) {


arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}

public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}

String smsMessageStr = address + "\n";


smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}

activity_sms.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/MainLayout"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="SMS Inbox"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />

<ListView android:id="@+id/SMSList"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_margin="5dp" />

</LinearLayout>

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

6 Marks

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


MainActivity.java file.
package com.android_examples.captureimagecamera_android_examplescom;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button button ;
ImageView imageView ;
Intent intent ;
public static final int RequestPermissionCode = 1 ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = (Button)findViewById(R.id.button);
imageView = (ImageView)findViewById(R.id.imageView);

EnableRuntimePermission();

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

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

startActivityForResult(intent, 7);

}
});
}

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

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

if (requestCode == 7 && resultCode == RESULT_OK) {

Bitmap bitmap = (Bitmap) data.getExtras().get("data");

imageView.setImageBitmap(bitmap);
}
}

public void EnableRuntimePermission(){

if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CAMERA))
{

Toast.makeText(MainActivity.this,"CAMERA permission allows us to Access CAMERA


app", Toast.LENGTH_LONG).show();

} else {

ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);

}
}

@Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

switch (RC) {

case RequestPermissionCode:

if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

Toast.makeText(MainActivity.this,"Permission Granted, Now your application can


access CAMERA.", Toast.LENGTH_LONG).show();

} else {

Toast.makeText(MainActivity.this,"Permission Canceled, Now your application


cannot access CAMERA.", Toast.LENGTH_LONG).show();

}
break;
}

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
}

}
activity_main.xml layout file.
<?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:id="@+id/activity_main"
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.captureimagecamera_android_examplescom.MainA
ctivity"
android:orientation="vertical"
android:background="#FFF9C4">

<ImageView
android:layout_width="fill_parent"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:id="@+id/imageView" />

<Button
android:text="Click here to capture image using camera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button" />

</LinearLayout>

Code for AndroidManifest.xml file.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android_examples.captureimagecamera_android_examplescom">

<uses-permission android:name="android.permission.CAMERA" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
<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>

2. Develop a program to send an email.

activity_main.xml

Drag the 2 EditTexts, 1 MultiLine EditText, 3 TextViews and 1 Button from the pallete, now
the activity_main.xml file will like this:

File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="22dp"
android:layout_marginTop="16dp"
android:ems="10" />

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="18dp"
android:ems="10" >

<requestFocus />
</EditText>

<EditText

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginTop="28dp"
android:ems="10"
android:inputType="textMultiLine" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="To:" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Subject:" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText3"
android:layout_alignBottom="@+id/editText3"
android:layout_alignParentLeft="true"
android:text="Message:" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_below="@+id/editText3"
android:layout_marginLeft="76dp"
android:layout_marginTop="20dp"
android:text="Send" />

</RelativeLayout>

Activity class

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
Let's write the code to send email via intent.

File: MainActivity.java

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 :"));

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....

});
}

@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;
}

3. Write a program to locate user’s current location. (Write ONLY .java and manifest file)

Androidmanifest.xml

<manifest ... >


<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>

Mainactivity.java

package com.javapapers.android.geolocationfinder;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

import android.util.Log;

public class MainActivity extends Activity implements LocationListener{


protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;

@Override

Computer Engineering Department Mrs. Chavan P.P.


STUDY SHADES.....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);

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


locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}

@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}

@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}

Computer Engineering Department Mrs. Chavan P.P.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy