Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 73

6.

Security and Application Deploument


• SMS Telephony
The telephony system is a software framework to mobile phones with
telephony provide functionalities, such as voice call, Video call, SMS,
MMS, data service, network management and so on. The android
telephony class provides information about the telephony services such
as subscriber id, sim serial number, phone network type etc.
• Sending and Receiving SMS Messages
• Android smartphones can send and receive messages to or from any other phone that
supports Short Message Service (SMS).
You have two choices for sending SMS messages:
• Use an implicit Intent to launch a messaging app with the ACTION_SENDTO intent
action.
• This is the simplest choice for sending messages. The user can add a picture or other
attachment in the messaging app, if the messaging app supports adding attachments.
• Your app doesn't need code to request permission from the user.
• If the user has multiple SMS messaging apps installed on the Android phone, the App
chooser will appear with a list of these apps, and the user can choose which one to use.
(Android smartphones will have at least one, such as Messenger.)
• The user can change the message in the messaging app before sending it.
• The user navigates back to your app using the Back button.
• Send the SMS message using the sendTextMessage() method or other methods of the
SmsManager class.
• This is a good choice for sending messages from your app without having to use
another installed app.
• Your app must ask the user for permission before sending the SMS message, if the user
hasn't already granted permission.
• The user stays in your app during and after sending the message.
• You can manage SMS operations such as dividing a message into fragments, sending a
multipart message, get carrier-dependent configuration values, and so on.
• To receive SMS messages, use the onReceive() method of the BroadcastReceiver
class.
Android - Sending SMS (tutorialspoint.com)
6.2 Location Based Service
• Developing applications for mobile devices gives us a lot more opportunities for
context based information than a traditional web application.
• One of the inputs for context sensitive information is the users current location.
• Android location APIs make it easy for you to build location-aware applications,
without needing to focus on the details of the underlying location technology.
• This becomes possible with the help of Google Play services, which facilitates
adding location awareness to your app with automated location tracking, geofencing,
and activity recognition.

• The Location Object:


• 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 getLatitude()
Get the latitude, in degrees.
4 double getLongitude()
Get the longitude, in degrees.
5 float getSpeed()
Get the speed if it is available, in meters/second over ground.
6 boolean hasAccuracy()
True if this location has an accuracy.
7 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:
To get the current location,
• create a location client which is LocationClient object,
• connect it to Location Services using connect() method,
• and then call its getLastLocation() method.
• This method returns the most recent location in the form of Location object that contains latitude and
longitude coordinates and other information as explained above.
• To have location based functionality in your activity, you will have to implement two interfaces −
•GooglePlayServicesClient.ConnectionCallbacks
•GooglePlayServicesClient.OnConnectionFailedListen
• Location Quality of Service:
Quality of Service(QoS) is enabled through the location request object. Location request object
requests the proper and accurate location. You can find below the methods that help in the process.
•setPriority(int priority) – It allows us to mark the request with priorities. The higher priority request
is executed first.
•setInterval(long millisecond) – It allows us to set the intervals on which we seek the location
updates.
•setExpirationDuration(long millisecond) – It allows us to set the duration of the request after which
it shall stop.
•setExpirationTime(long millisecond) – It allows us to decide the expiration time of our request.
•setNumUpdates(int number) – It allows us to set the number of updates we require for a particular
place.
• Displaying a Location Address
• Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given
latitude and longitude.
• This method is synchronous, and may take a long time to do its work, so you should call the method from
the doInBackground() method of an AsyncTask class.
• The AsyncTask must be subclassed to be used and the subclass will override doInBackground(Params...) method
to perform a task in the background and onPostExecute(Result) method is invoked on the UI thread after the
background computation finishes and at the time to display the result.
• There is one more important method available in AyncTask which is execute(Params... params), this method
executes the task with the specified parameters.
• Geocoders:
Geocoders are modules present in the Location framework that help convert latitude longitude to
human-readable addresses and vice versa.
Usually, an address may come in two formats:
1. Latitude Longitude coordinates of the place.
2. Human readable address of the place.
Now for a device. “Chira Chas, Bokaro, Jharkhand, India” is not an understandable address. For us as
humans, we can understand the above address. But to make it machine-understandable, we need
geocoders. Geocoders will convert the above address to its respective latitude and longitude.
Now for the other scenario, suppose you got an address as “ latitude-39.98824 and longitude-
134.68742”. Did you understand where it is? Obviously No. So here also geocoders come into the
picture. It converts the given latitude and longitude to human-readable addresses.
We can classify the task of geocoder in the following manner:
1. Forward Geocoding-
Forward Geocoding implies translation of human-readable addresses to latitude and longitudes.
2. Reverse Geocoding –
Reverse Geocoding implies translation of latitude longitude-based address to human-readable address.
• Get the Last Known Location
• It’s always a better practice to keep track of your last known location. Your system uses your last known
location to send you updates based on location. You can get your last known location by calling the
getLastLocation() method.
• Below is eg of same.
private lateinit var fusedLocationClient:
FusedLocationProviderClient override fun onCreate(savedInstanceState: Bundle?)
{ //Create a Location Client object
LocationClientObject = LocationServices.getFusedLocationProviderClient(this)
}
Now just call the last location method with a listener.
Code:
LocationClientObject.lastLocation .addOnSuccessListener
{
location : Location? ->
// you got the location object // the location object has the latitude and
longitude of the place. //In some cases it may contain null.
}
Request Location Update
To get timely location updates, you can call the requestLocationUpdates() method from the onResume()
method of the activity.
• Creating API keys
The API key is a unique identifier that authenticates requests associated with your project
for usage and billing purposes. You must have at least one API key associated with your
project.
To create an API key:
1.Go to the Google Maps Platform > Credentials page.
2.Go to the Credentials page
3.On the Credentials page, click Create credentials > API key.
The API key created dialog displays your newly created API key.
4.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.)
Restricting API keys
Google strongly recommends that you restrict your API keys by limiting their usage to those
only APIs needed for your application. Restricting API keys adds security to your
application by protecting it from unwarranted requests.
How to Generate API Key for Using Google Maps in Android?
For using any Google services in Android, we have to generate an API key or we have to generate some unique key
for using that service provided by Google. So Maps is one of the famous and most used services provided by Google.
Maps can be seen in each and every app provided by Google and we also can use that service to add maps to our
app.

https://developers.google.com/maps/documentation/android-sdk/get-api-key
https://abhiandroid.com/programming/googlemaps

https://
www.geeksforgeeks.org/how-to-
use-different-types-of-
google-maps-in-android/

https://www.tutlane.com/tutorial/android/
android-google-maps-api-with-examples
• Android Google Map:
• Android provides facility to use and integrate Google map in our Application. It
navigates location direction, displays your current location, search location etc.

• Types of Google Maps:


• There are four types of maps available within the Maps JavaScript API.
• To customize the Google map, there are four types of maps provide.
• ROADMAP: This type of map shows the street view of the specific area. It is the
default type map.
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

• SATELLITE: This type of map shows the satellite images of the specific area.
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
• HYBRID: This type of map shows the major streets of the specific area.
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

• TERRAIN: This type of map shows the terrain and vegetation.


googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
ZoomControls in Android

https://www.geeksforgeeks.org/zoomcontrols-in-android-with-example/
Markers:
Markers indicate single locations on the map. You can customize your markers by
changing the default color, or replacing the marker icon with a custom image.
Markers identify locations on the map. The default marker uses a standard icon, common
to the Google Maps look and feel. It's possible to change the icon's color, image or
anchor point via the API. Markers are objects of type Marker, and are added to the map
with the GoogleMap.addMarker(markerOptions) method.
Add a marker
The following example demonstrates how to add a marker to a map. The marker is created
at coordinates -33.852,151.211 (Sydney, Australia), and displays the string 'Marker in
Sydney' in an info window when clicked.
JavaKotlin

@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions()
.position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
• Location Data:
The location data available to an Android device includes the current location of the
device — pinpointed using a combination of technologies — the direction and method of
movement, and whether the device has moved across a predefined geographical
boundary, or geofence. Depending upon the needs of your application, you can choose
between several ways of working with location data:
•The My Location layer provides a simple way to display a device's location on the
map. It does not provide data.
•The Google Play services Location API is recommended for all programmatic requests
for location data.
•The LocationSource interface allows you to provide a custom location provider.
Location permissions:
If your app needs to access the user's location, you must request permission by
adding the relevant Android location permissions to your app.
Android offers two location permissions:
ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
Add the permissions to the app manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>
However, if precise location is needed, then add
both ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION
permissions to your app's manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>
https://www.tutorialspoint.com/how-to-request-location-permission-at-run-time-in-android
• Android Security Model
Android Security Program includes:
• Design review: Android security process focuses in the development
lifecycle with the formation of configurable security model and
design. feature of the platform is reviewed by engineering and
security resources, with suitable security controls combined into the
architecture of the system.
• Penetration testing and code review :
In Development of the platform Android-created and open source
mechanisms are subject to dynamic security reviews. These reviews are
performed by the Google's Information Security Engineering team,
Android Security Team and independent security consultants. The main aim of
these reviews is to identify weaknesses and possible vulnerabilities well before
major releases, and to simulate the types of analysis that are performed by external
security experts upon release.
• Open source and community review: AOSP enable broad security review by any
interested party. open source technologies that have undergone significant
external security review, such as the Linux kernel used by the android.
• Incident response: security issues may occur after shipping, which is why the
Android project has created a comprehensive security response process. To
slove security issue Android security team members monitor the Android-
specific and the general security community for discussion of potential
• Monthly security updates: The Android security team provides monthly updates to
Google Android devices and all our device manufacturing partners.
A. Platform security architecture
Android pursues to be the most safe and usable operating system for mobile platforms by
repurposing traditional operating system security controls to:
• Protection for app and user data
• Protection of system resources (including the network)
• Android app isolation from the system,

 To achieve these objectives, Android provides these key security features:


• Security and Application Deployment
• Strong security at the OS level through the Linux kernel
• Mandatory app sandbox for all apps
• Secure interprocess communication
• App signing
• App-defined and user-granted permissions
 The Android Platform Security Model. Specifically we discuss:

• The security model informed the Android platform's security design from the beginning, but has not
been formally published or described outside of Google.
• The context in which this security model must operate, including the scale of the Android ecosystem
and its many form factors and use cases.
• The complex threat model Android must address.
• How Android's reference implementation in the Android Open Source Project (AOSP) enacts the
security model.
• How Android's security systems have evolved over time to address the threat model.
• B .Using Permissions
• Android application cannot do anything that would adversely impact the user experience or any
data on the device. To make use of protected features of the device, you must include in your
AndroidManifest.xml one or more <uses-permission> tags declaring the permissions that your
application needs.
• For example, an application that needs to monitor incoming SMS messages would specify:
<manifest
xmlns:android="https://schemas.android.com/apk/res/an
droid"
package="com.android.app.myapp">
<uses-permission
android:name="android.permission.RECEIVE_SMS" />
</manifest>
• At application install time, permissions requested by the application are granted to it by the
package installer, based on checks against the signatures of applications declaring those
permissions and/or interaction with the user. No checks with the user are done while an
application is running: it either was a particular permission when installed, and granted can use
that feature as desired, or the permission was not granted and any attempt to use the feature will
fail without prompting the user.
• Often times a permission failure will result in a back to the SecurityException being thrown
application. However, this is not guaranteed to occur everywhere. For example, the
sendBroadcast(Intent) method checks permissions as data is being delivered to each receiver,
after the method call has returned, so you will not receive an exception if there are permission
failures. In almost all cases, however, a permission failure will be printed to the system log.
• The permissions provided by the Android system can be found at Manifest.permission. Any
application may also define and enforce its own permissions, so this is not a comprehensive list
of all possible permissions.
• A particular permission may be enforced at a number of places during your
program's operation:

‣ At the time of a call into the system, to prevent an application from executing
certain functions.
‣ When starting an activity, to prevent applications from launching activities of
other applications.
‣ Both sending and receiving broadcasts, to control who can receive your
broadcast or who can send a broadcast to you.
‣ When accessing and operating on a content provider.
‣ Binding or starting a service.
• 6.3.1 Declaring and Enforcing Permissions
• To enforce your own permissions, you must first declare them in your AndroidManifest.xml using one or more
<permission> tags.
• For example, an application that wants to control who can start one of its activities could declare a permission for this
operation as follows:
<manifest
xmlns:android="https://schemas.android.com/apk/res/android"
package="com.me.app.myapp">
<uses-permission
android:name=“com.me.app.myapp.permission.DEADLY_ACTIVITY”/>
android:label="@string/permlab_deadly Activity"
android:description="@string/perm
android.permissionGroup="android.permission- group.COST MONEY"
android:protectionLevel="dangerous" />
</manifest>
• The <protectionLevel> attribute is required, telling the system how the user is to
be informed of applications requiring the permission, or who is allowed to hold
that permission, as described in the linked
documentation.
• The <permissionGroup> attribute is optional, and only used to help the system
display permissions to the user. You will usually want to set this to either a
standard system group (listed in android.Manifest.permission_group) or in more
rare cases to one defined by yourself. It is preferred to use an existing group, as
this simplifies the permission UI shown to the user.
• Note that both a label and description should be supplied for the permission.
These are string resources that can be displayed to the user when they are viewing
a list of permissions (android:label) or details on a single permission
(android:description). The label should be short, a few words describing the key
piece of functionality the permission is protecting. The description should be a
couple sentences describing what the permission allows a holder to do. Our
convention for the description is two sentences, the first describing the
permission, the second warning the user of what bad things can happen if an
application is granted the permission.
• Here is an example of a label and description for the CALL PHONE permission:
• <string name="permlab_callPhone">directly call phone numbers</string>
<string name="permdesc_callPhone">Allows the application to call
phone numbers without your intervention. Malicious applications may
cause unexpected calls on your phone bill. Note that this does not
allow the application to call emergency numbers.</string>
• You look at the permissions currently defined in the system with the shell command adb shell pm list
permissions. In particular, the '-s' option displays the permissions in a form roughly similar to how the user will
see them:
• $ adb shell pm list permissions –s
• All Permissions
• Network communication: view Wi-Fi state, create Bluetooth connections, full
• Internet access, view network state
• Your location: access extra location provider commands, fine (GPS) location,
• mock location sources for testing, coarse (network-based) location
• Services that cost you money: send SMS messages, directly call phone numbers
• 5.3.2 Using Custom Permissions:
• Android allows defining custom permissions with your application.
• If you wanted to avoid certain users from starting one of the activities in your
application, programmer could do that by defining a custom permission.
• To use custom permissions, you first declare them in your AndroidManifest.xml file.
• Once you've defined permission, you can then refer to it as part of your component
definition.
• We'll show you how this works.
Let's create an application containing an activity that not everyone is allowed to start.
Instead, to start the activity, a user must have a specific permission. Onceyou have
the application with a privileged activity, you can then write a client that knows how
• First create the project with the custom permission Android Application and activity.
• Open the Android Development IDE and select New > New Project > Android Project.
This will open the "New Android Project" dialog box.
• Enter Custom Permission as the project name, select the "Create new project in
workspace" radio button, and mark the "Use default location" check box. Enter
com.cust.perm as the package name, CustPermMainActivity as the activity name, and
Custom Permission as the application name. Click the Finish button to create the
project. The generated project will have the activity you just created, which will serve as
the default (main) activity. Let's also create a so-called privileged activity-an activity
that requires a special permission. In the Eclipse IDE, go to the com.cust.perm package,
create a class named PrivActivity, use the following code.
The PrivActivity Class package com.cust.perm;
importandroid.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams; import
android.widget.LinearLayout;
import android.widget.TextView;
public class PrivActivity extends Activity {
Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); LinearLayout view = new
LinearLayout(this);
view.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
view.setOrientation (LinearLayout.HORIZONTAL);
• To enforce your own permissions, you must first declare them in your AndroidManifest.xml using one
or more <permission> elements.
Example
For example, an app that needs to control which other apps can start one of its activities can declare a
permission for this operation as follows:
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >

<permission
android:name="com.example.myapp.permission.DEADLY_ACTIVITY"
android:label="@string/permlab_deadlyActivity"
android:description="@string/permdesc_deadlyActivity"
android:permissionGroup="android.permission-group.COST_MONEY"
android:protectionLevel="dangerous" />
...
</manifest>
• The protectionLevel attribute is required and tells the system how to inform users of
apps requiring the permission or what apps can hold the permission.
• The android:permissionGroup attribute is optional and only used to help the system
display permissions to the user
• The label is short: a few words describing the key piece of functionality the permission
is protecting.
• The description is a couple of sentences describing what the permission lets a holder
do.
• The <permission-group> element defines a label for a set of permissions—both those
declared in the manifest with <permission> elements and those declared elsewhere.
This affects only how the permissions are grouped when presented to the user.
6.4 Generate Signed APK for Android App
-
To publish an app in Google play store, first we need to generate signed APK version of our application, for that
that open your application in android studio and select Build→ Generate Signed APK option like as shown below.
https://www.geeksforgeeks.org/how-to-generate-signed-apk-in-android-studio/
Generate Signed Apk:
Signed Apk generates a key and this key can be used to release versions of the app, so it is important to
save this key which will be used when the next version of the app is released. The Android system
needs that all installed applications be digitally signed with a certificate whose private key is owned by
the application’s developer. The Android system applies the certificate as a means of recognizing the
author of an application and establishing trust relations between applications. The essential points to
understand about signing Android applications are:
•When developers are ready to publish the android application for end-users, they are required to sign it
with a suitable private key. They can’t publish an application that is signed with the debug key
generated by the SDK tools.
•Applications can only be installed when they are signed. Android does not allow unsigned applications
to get installed.
•Developers can apply self-signed certificates to sign the application. No certificate authority is required
•To test and debug the application, the build tools sign the application with a special debug key that is
created by the Android SDK build tools.
•The system will test a signer certificate’s expiration date only at install time. If an application’s signer
license expires after the application is installed, the application will continue to operate normally.
Importance of Signed Apk:

•Application Modularity: The applications signed by the same process are recognized as a single
application and are allowed to run on the same process. This allows the developers to make the
application in modules and so users can update each module independently.
•Application Upgrade: To update the application, the updates must be signed with the same
certificates. When the system is installing an update to an application, it relates the certificate in the
new version with those in the actual version. If the certificates match correctly, including both the
certificate data and order, then the system releases the update. If we sign the new version without
using matching certificates, we need to attach a different package name to the application and in this
case, the user installs the new version as a completely new application.
•Code/Data Sharing Through Permissions: To allow the applications to use different resources,
Android system executes signature-based permissions enforcement so that the application can
exhibit functionality to another application which is signed with a specified certificate. By signing
various applications with the same certificate and working with signature-based permissions checks,
your applications can yield code and data in a secure manner.
Generating Signed Apk in Android Studio
Step 1: Go to Build -> Generate Signed Bundle or APK, a pop up will arise. Choose APK in the pop-up and click
on Next.
Step 2: After completing step 1, if you already have a key, make sure you just refer to that and you can release the
version of that app but in case if it is the first time it is recommended to create a new key. After creating a new key click
on OK and then click on Next.
Step 3: After clicking Next in the next pop-up make sure to choose release as Build Variants and check the
two Signature Versions as well. Then click on Finish.
Step 4: After successfully completed these steps you can locate your signed apk at app -> release ->
app-release as your apk file.
Publish Android App On PlayStore
Step 1: First generate signed apk of your Android App to publish it on Play Store.
Step 2: Now you will need to sign up for Google Play Console to publish and manage your Android App.
Important Note: You can signup with this link https://play.google.com/apps/publish/
Step 3: Login with your Gmail account that you want to use for publishing App on Play Store.
Step 4: Now there are 4 steps to complete the registration for Google play store console. You have already completed two.

Step 5: After reading the Google play store developer distribution agreement agree to their terms by clicking on check
box
Step 6: Now you will need to pay one time ‘Developer Registration Fee’ of $25 to Google. Please fill your credit card
details to make the payment.
Important Note: You can upload unlimited number of Android App on Play store from single account with a limit of
uploading 15 apk/day.
Step 7: Complete your account details for Google developer account. For example see the below image:
Step 8: Now click on Create Application
Step 9: Enter the name of your App.
Step 10: Now fill store listing details of your App which include Title, Short description, and Full description.
Step 11: After this you need to put some App screenshots here. The minimum required are 2 screenshots and maximum limit
is 8.
Step 12: After screenshot now you need to put a high Resolution icon or logo with a size of 512 * 512 pixel. This will be
displayed on Play Store.
After that another mandatory thing is you need to put a feature graphic of 1024 * 500 pixel dimension. See below
image for more detail.
Step 13: Now scroll down and fill other details which include application type, category, website, email and phone no.
After this check privacy policy because now we are not submitting and then click on save draft. If your App require
user permission then it is mandatory to put privacy url.
Click on Save Draft to save your work so far.
Step 14: After saving data on draft now go to app release and click on manage production.

Step 15: Now you will see create release now click on it.
Step 16: After click on create release you will see browse files click on it and upload your signed APK.

Step 17: Once the upload is successful then scroll down and click on review to check.
Step 18: Now go to Content Rating and click on continue.
Step 19: Fill details which include email address and select your categories.
Step 20: Now select Violence, Sexuality, Language, Controlled Substance and Miscellaneous based on your App. First click
on save questionnaire for save and then click on calculate rating.
Step 21: Now click on apply rating.
Step 22: Click on pricing and distribution and select free/paid based on how you want user to access your App.
Step 23: Now scroll down and see mandatory things with * you need to select After this click on save draft .
Step 24: Now Click on ready on publish along with save draft and click on Manage release.
Step 25: Click on Manage Production.

Step 26: After Manage production click on edit release.


Step 27: Now click on review.

Step 28: After review click on Start Rollout to production. Now you need to confirm. After confirm you will need
to wait for one or six hour for approval.

You might also like