0% found this document useful (0 votes)
14 views43 pages

Unit 6

The document discusses SMS, email, and location services in Android applications. It provides details on sending SMS and email through Android APIs and describes methods for getting the current location and customizing maps.

Uploaded by

Vinayak Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views43 pages

Unit 6

The document discusses SMS, email, and location services in Android applications. It provides details on sending SMS and email through Android APIs and describes methods for getting the current location and customizing maps.

Uploaded by

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

Unit 6

Security And Application Development


SMS Telephony
• Provide services for all text-based SMS messages. Following are classes of SMS Telephony.

1. Telephony.Sms.Conversations
2. Telephony.Sms.Draft
3. Telephony.Sms.Inbox
4. Telephony.Sms.Intents
5. Telephony.Sms.Outbox
6. Telephony.Sms.Sent
Android - Sending SMS

• In Android, you can use SmsManager API or devices Built-in SMS application to send
SMS’s.
• SMSManager class manages operations like sending a text message, data message, and
multimedia messages (MMS).
• For sending a text message method sendTextMessage() is used likewise for multimedia
message sendMultimediaMessage() and for data message sendDataMessage() method
is used.
• SmsManager API

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
• need SEND_SMS permission.

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


Function Description
sendTextMessage(String destinationAddress,
sendTextMessage() String scAddress, String text, PendingIntent sentIntent,
PendingIntent deliveryIntent, long messageId)
sendDataMessage(String destinationAddress,
sendDataMessage() String scAddress, short destinationPort, byte[] data,
PendingIntent sentIntent, PendingIntent deliveryIntent)
sendMultimediaMessage(Context context,
sendMultimediaMessage() Uri contentUri, String locationUrl,
Bundle configOverrides, PendingIntent sentIntent
Android - Sending Email
• Email is messages distributed by electronic means from one system user to one or more
recipients via a network.
• To send an email from your application, you don’t have to implement an email client from
the beginning, but you can use an existing one like the default Email app provided from
Android, Gmail, Outlook, K-9 Mail etc.
• For this purpose, we need to write an Activity that launches an email client, using an
implicit Intent with the right action and data.
Intent Object - Action to send Email

• use ACTION_SEND action to launch an email client installed on your Android device.
Syntax to create an intent with ACTION_SEND action.

Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email

To send an email you need to specify mailto: as URI using setData() method and data type
will be to text/plain using setType() method as follows −

emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
Intent Object - Extra to send Email

Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached
to the intent before sending the intent to a target email client. You can use following extra
fields in your email −
Sr. No. Extra Data & Description
1 EXTRA_BCC-A String[] holding e-mail addresses that should be blind carbon copied.
2 EXTRA_CC-A String[] holding e-mail addresses that should be carbon copied.
3 EXTRA_EMAIL-A String[] holding e-mail addresses that should be delivered to.

4 EXTRA_HTML_TEXT-A constant String that is associated with the Intent, used with ACTION_SEND to
supply an alternative to EXTRA_TEXT as HTML formatted text.

5 EXTRA_SUBJECT-A constant string holding the desired subject line of a message.

EXTRA_TEXT-A constant CharSequence that is associated with the Intent, used with ACTION_SEND to
6
supply the literal data to be sent.

7 EXTRA_TITLE-A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER.
Example

emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]{"Recipient"});


emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT , "Message Body");
Location Based Services
The Location object represents a geographic location which can consist of a latitude,
longitude, time stamp, and other information such as bearing, altitude and velocity.
There are following important methods which you can use with Location object to get location
specific information

Sr.No. Method & Description


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.
11 boolean hasSpeed()-True if this location has a speed.

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.


Get the Current Location
Get the API key

• Visit the Google Cloud Platform Console.

• Click the project drop-down and select or create the project for which you want to add an API key.

• Click the menu button and select APIs & Services > Credentials.

• On the Credentials page, click Create credentials > API key.


The API key created dialog displays your newly created API key.

• Click Close.
The new API key is listed on the Credentials page under API keys.
(Remember to restrict the API key before using it in production.)
Add the API key to your app

Follow the steps below to include the API key in your application's manifest, contained in the file
AndroidManifest.xml.
1. In AndroidManifest.xml, add the following element as a child of the <application> element, by
inserting it just before the closing </application> tag:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>

In the value attribute, replace YOUR_API_KEY with your API key (the encrypted string). This element
sets the key com.google.android.geo.API_KEY to the value of your API key.
2. Save AndroidManifest.xml and re-build your application.
Android Google Map

Android allows us to integrate google maps in our application. You can show any location on the
map , or can show different routes on the map e.t.c. You can also customize the map according to
your choices.

Google Map - Layout file


Now you have to add the map fragment into xml layout file. Its syntax is given below −
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Google Map - AndroidManifest file
<!--Permissions-->

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


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!--Google MAP API key-->

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
Customizing Google Map

You can easily customize google map from its default view , and change it according to your demand.
Adding Marker
You can place a maker with some text over it displaying your location on the map. It can be done by via
addMarker() method. Its syntax is given below −

final LatLng TutorialsPoint = new LatLng(21 , 57);


Marker TP = googleMap.addMarker(new
MarkerOptions().position(TutorialsPoint).title("TutorialsPoint"));
Changing Map Type

You can also change the type of the MAP. There are four different types of map and each give a different
view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
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.
Methods of Google map
Methods Description
addCircle(CircleOptions options) This method add circle to map.
addPolygon(PolygonOptions options) This method add polygon to map.
addTileOverlay(TileOverlayOptions
options) This method add tile overlay to the map.

animateCamera(CameraUpdate This method moves the map according to the update with an
update) animation.
clear() This method removes everything from the map.
getMyLocation() This method returns the currently displayed user location.
This method reposition the camera according to the instructions
moveCamera(CameraUpdate update) defined in the update.
setTrafficEnabled(boolean enabled) This method set the traffic layer on or off.
snapshot(GoogleMap.SnapshotReadyC
This method takes a snapshot of the map.
allback callback)
stopAnimation() This method stops the camera animation if there is any progress.
Geocoding and 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.
How to Get Current Location in Android

There are two ways to get the current location of any Android device:
1.Android’s Location Manager API
2.Fused Location Provider: Google Play Services Location APIs

Define uses permissions for location access in the manifest file

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


<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<!– Required only when requesting background location access on Android 10 (API level 29) –>
<uses-permission android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />
Generate Signed Bundle/APK for Android APP
When you are ready to publish your app, you need to sign your app and
upload it to an app store, such as Google Play.
When publishing your app to Google Play for the first time, you must also
configure Play App Signing.
Steps to Generate Signed Bundle/APK(Generate an upload key and keystore)

1. In the menu bar, click Build > Geerate Signed


Bundle/APK.
2. In the Generate Signed Bundle or APK dialog, select
Android App Bundle or APK and click Next.
3. Below the field for Key store path, click Create new.
4. On the New Key Store window, provide the following
information for your keystore and key, as shown in
figure.
5. Keystore
• Key store path: Select the location where your
keystore should be created. Also, a file name should be
added to the end of the location path with the .jks
extension.
•Password: Create and confirm a secure password for
your keystore.
6.Key
•Alias: Enter an identifying name for your key.
•Password: Create and confirm a secure password for your key. This should be the same as your keystore
password. (Please refer to the known issue for more information)
•Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for
at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
•Certificate: Enter some information about yourself for your certificate. This information is not displayed
in your app, but is included in your certificate as part of the APK.
7. Once you complete the form, click OK.
8. If you would like to build nd sign your app with your upload key, continue to the section about how to
Sign your app with your upload key. If you only want to generate the key and keystore, click Cancel.
How to Publish Your Android App on Google Play Store?
Step 1: Make a Developer Account
A developer account is must be needed to upload an app on the Google Play Store.
The account can be created in four simple steps:
Sign-In with Your Google Account
Accept Terms
Pay Registration Fee of $25.
Complete Your Account Details
Step 2: After you completed step 1 you will be redirected to this page where you have to click on the CREATE
APPLICATION button.
Once you click on it a pop up will be shown then you have to choose your Default language and Title of your app. Then click
on the CREATE button.
Step 3: Store listing
After you completed step 2 you will be redirected to this page where you have to provide the Short description and Full
description of your App.
Then you scroll down the page and now you have to add the Hi-res icon of your app.
Then you have to provide the Screenshots of your app.
And next thing you have to provide is the Feature Graphic of your app. Note that this graphic is then used everywhere your
app is featured on Google Play.
Then come to Categorization part where you have to provide your Application type and Category of your app.
Then come to Contact details part where you have to provide your Website(if any), email, and Phone of yours.
And finally when you click on SAVE DRAFT button you can see that Store listing tab is now become turned to green and
you are done for Store listing.
Step 4: App release
After completing step 3 go to App releases then scroll down to Production track and click on MANAGE button.
After redirecting to the next page click on the CREATE RELEASE button.
After that on the next page, you have to upload your APK file in Android App Bundles and APKs to add section.
After that simply click on the SAVE button.
Step 5: Content rating
Now after completing step 4 go to Content rating and click on CONTINUE button.
After that fill your email address as well as confirm the email address.
And then Select your app category.
After selecting your app category make sure that you read all of these and answer them correctly.
And after answering them correctly don’t forget to click on SAVE QUESTIONNAIRE button.
Once you saved all those things then click on CALCULATE RATING button.
When you redirected to another page scroll down and click on APPLY RATING button. And you are done for Content
rating section. Don’t forget to notice that Content rating section is now become turned to green.
Step 6: Pricing & distribution
Then go to the Pricing & distribution section. Then select the country in which you want to available your app.
Then go down and down and check out the Content guidelines and US export laws section by marking them tick mark.
And click on the SAVE DRAFT button. Don’t forget to notice that Pricing & distribution section is now become turned to
green tick.
Step 7: App content
Then come to the App content section. And in the Privacy policy section click on the Start button.
And then provide a valid Privacy policy URL. Note that google will check this.
Then go back and continue further steps by clicking start button in Ads section.
Then select does your app contain ads or not? And click on SAVE button.
Then again go back and continue further steps by clicking start button in Target audience and content section.
In the next page select the Target age group and scroll down and click on the Next button.
Then check the Appeal to children section. And click on the Next button.
On the next page click on the Save button and you are done for App content section.
Step 8: App releases
Again go back to the App releases section. And in the Production track click on the EDIT RELEASE button.
Then on the next page go down and down and click on the REVIEW button.
And finally, on the next page click on the START ROLLOUT TO PRODUCTION button to send your app to review. And
you are finally done.
After usually 4 to 5 days they will review your app and let you know to either approve or reject your app.
Android Security Model
The security model is based on the consent of the following parties:
1.Operating System
2.Application
3.End-User
For an action to be successfully executed, all three parties must agree on it.
End User
• Since Android is primarily focused on the end user, the system has to be secure by
default.

• The user expects the other two parties to have taken the necessary measures to ensure
his safety.
• However, when the nature of the action requires his consent, the end-user is the
decisive factor when it comes to the security of the overall system.
Operating System Security

• The kernel is the core operating system software that handles the CPU resources, the
system memory, the system devices, including the file systems and networking, and is
responsible for managing all the processes.
• It serves as a link between the software and the hardware.
• Android’s kernel is based on the Linux kernel’s long-term support (LTS) branches.
• The decades of continuous improvement have established Linux as a stable and reliable
kernel amongst many businesses and security professionals.
• The security of the Android operating system is based around the following key
security features of the Linux kernel:

Process Isolation
User-Based Permission Model
Inter-Process Communication (IPC)
Sandboxing¹

Android platform uses the Linux user-based permissions model to isolate application
resources.
This process in called application sandbox.
The aim of sandboxing is to prevent malicious external programs from interacting with
the protected app.
The internal operating system components are also protected by the sandboxing
mechanism.
Android uses the User ID (UID) concept to manage an application’s access control and not
the system user’s access control. An application is prohibited from accessing other
application’s data or system features without the necessary permissions.

The application is sandboxed at the kernel level, hence it is guaranteed that the
application is isolated from the rest of the system, regardless of specific development
environment, programming languages or APIs used.

By default, applications have limited access to the operating system. This ensures that a
malicious application cannot get access to the external system from the inside.
Rooting
• To overcome the limitations of the sandbox model, the user is able to root the device. On a Linux system,
root is the name of the account that has access to all files and commands. Being based on Linux, Android
has this concept as well.

• Although counterintuitive, the owner of the device is NOT root. This design decision was made for security
reasons. If the owner was able to do anything in the system, it would be easier for malicious applications to
get control over the entire system by tricking the user into granting them the same permissions.

• But as we’ve already seen, Android is designed to be open. Consequently, the user is allowed to root the
phone, i.e. switch to the root user.

• It should be noted that rooting is not recommended to be done by inexperienced users. Rooting a phone
might result in making the warranty null and void. One should always weight the advantages and
disadvantages of rooting before proceeding.

• After rooting, we can no longer rely on the security measures enforced by the operating system. This means
that we are effectively taking the whole system into our own hands, have control over everything, and
dispose the beautifully engineered security systems in favour of a customised experience.
Verified Boot³
• Verified Boot is a process that ensures that the device is booting the original operating system alongside the
afferent system code, and not a malicious replica.
• Similarly to the Blockchain technology, the Verified Boot establishes a chain of trust between the multiple
components that can be altered, starting from the hardware up to the verified partitions. If any of the
components up the chain is altered, the whole chain is invalidated and the user is warned.
• The device state can be one of the following:
• LOCKED: no custom software can be flashed on the device and boot verification is active
• UNLOCKED: custom software can be flashed on the device and boot verification is inactive
• Root of trust is a cryptographic key used to sign the Android copy that runs on the device. This key is part of the
boot verification. We are able to replace this key in order to run custom Android versions. By doing so, we can
keep the verified boot mechanism even if we use a different OS version.
• Android is continuously delivering minor security updates alongside the major ones that come with every new
Android version.
• The minor updates usually patch discovered vulnerabilities.
• An attacker might try to downgrade the Android version running on the device in order to exploit vulnerabilities
that were patched. This class of attacks is mitigated by Rollback Protection. Rollback Protection is part of the
Verified Boot process.
2. Application Security
• The security aspect of an application is often overlooked. The lack of concern can determine the
application to transform into an attack vector, leveraged by malicious actors.
• Permissions⁴

• In Android, the user’s privacy is protected by the means of permissions. Android applications
requires the user’s consent to perform actions that might impact other applications, the operating
system or the user himself.

• The permissions required by an application are declared in the AndroidManifest.xml. Every


permission is specified in its own uses-permission tag.
• Some permissions are granted to the application by default when specified. However, the other
category of permissions, called dangerous permissions, require special consent from the user.

•Install-time permissions (for Android 5.1.1 and below): When an application is installed, the user is
presented with the list of all permissions that the app requires.
•Runtime permissions (for Android 6.0 and higher): When an application requests a permission, the user is
prompted with a dialog. Unlike install-time permissions, runtime permissions are usually requested when
the respective functionality is needed. For example, a camera permission should be requested before the
user tries to take a capture.
Data Storage⁵
Data storage is, allegedly, the most sensitive field of Android security. Data is the ultimate goal of an attacker. We
have to make sure that every option of data storage is properly secured according to the sensitivity of the data
saved.

Android provides three ways of saving data on the device :

Internal storage: Data stored here is visible only to the corresponding application. Other applications do not
have access to the files stored in the respective application’s directory. When the application is uninstalled, all the
data stored here is erased as well.
External storage: Data stored in external storage is globally readable and writable. This means that any
application can read or write the files stored here. Therefore, it is necessary for the application’s sensitive
information to be stored in the internal storage. However, in case the information can be safely saved publicly, we
should make the necessary validations when we try to read it back. Since the data can be altered by other
applications or attackers, we can’t be certain that the data we previously wrote didn’t transform into a dynamically-
loaded malware.
Content providers: They provide an abstraction over the data stored. With the use of content providers, we have
more control over the read and write permissions. If we develop multiple applications under the same signature,
we can share data between them with the use of a content provider, so that the data is visible only between our
applications.
A common developer habit is that of storing user’s credentials in the SharedPreferences.
However, we should design our data storage by thinking that everything stored can end up in the hands of an
attacker. All the permissions and protections can be nulled if the device is rooted.

To add an extra layer of security we can encrypt the data stored. To encrypt the data, Android provides the
Security⁷ library that includes, inter alia, two classes for data encryption:

EncryptedFile: Provides a custom implementation over FileInputStream and FileOutputStream, effectively


creating more secure data streams — data is encrypted and decrypted on every I/O operation
EncryptedSharedPreferences: Provides a secure layer over SharedPreferences. Automatically encrypts keys
and values using a two-scheme method.
Interprocess Communication (IPC)
The Android IPC mechanisms allow us to enforce security policies based on the relation between our
application and the other end.

Android provides the following classes that facilitate the interprocess communication:

Intent
Binder
Messenger
Intents are the go-to mechanism of passing data when working with activities or broadcast listeners.
Intents can be either explicit or implicit.

Explicit intents are designed to be received by an explicit component, hence the name. This way, we
can be sure that the data sent from application A is received only by the application B. Moreover,
explicit intents can be used to send data between activities inside our applications.

implicit intents specify an action that should be performed. Depending on the action, the intent might
include some data needed for the respective action.
Implicit intents are usually used when our application cannot do an action and we want to delegate
the task to a third-party application.

Binder and Messenger are used to implement remote procedure call (RPC) IPC in Android. They
provide an interface that facilitates secure communication between an application and a service.
Application Signing
• Code signing provides developers with the ability to identify the author of an application and
seamlessly update it, without the need of cumbersome processes. Applications that are not signed
by a developer cannot be uploaded to Google Play.

• Even if an unsigned application package ended up on the device, the application cannot be installed
because the package manager checks whether the package is signed or not before installing any
application.

• Application signing is the first step in the application sandbox mechanism.


• An UID is assigned based on the certificate used to sign the application.

• If multiple applications are signed using the same certificate, they can specify the
android:sharedUserId key in their manifest so that they share the same UID. However, the key was
deprecated in API 29 because it could cause non-deterministic behaviour when assigning the UID,
hence it is strongly discouraged to be used and may be removed in future versions.

• Applications have the ability to create security permissions protected by the signature. Thus,
applications signed under the same certificate, under different UIDs and application sandboxes, can
access restricted functionalities exposed by one or the other.

You might also like