0% found this document useful (0 votes)
10 views58 pages

Mad U6

This document provides a comprehensive guide on sending SMS and emails in Android applications, detailing two methods for SMS: using the SmsManager API and invoking the built-in SMS application via Intent. It also covers how to send emails using implicit Intents, including necessary permissions and the structure of the Intent object. Additionally, it introduces Google Maps integration in Android apps, explaining how to set up the Google Maps API and different types of maps available.
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)
10 views58 pages

Mad U6

This document provides a comprehensive guide on sending SMS and emails in Android applications, detailing two methods for SMS: using the SmsManager API and invoking the built-in SMS application via Intent. It also covers how to send emails using implicit Intents, including necessary permissions and the structure of the Intent object. Additionally, it introduces Google Maps integration in Android apps, explaining how to set up the Google Maps API and different types of maps available.
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/ 58

Unit 6

Security and Application Deployment

SMS Telephony

Sending and receiving SMS Message in Android

In Android, we can send SMS from an application in two ways.

If we use SmsManager api, it will directly send SMS from our application. In case
if we use Intent with proper action (ACTION_VIEW), it will invoke built-in SMS
app to send SMS from our application.
Any SMS sending requires add android.permission.SEND_SMS permission to the
manifest:
<uses-permission android:name="android.permission.SEND_SMS"/>

Check if device can send SMS


We can use TelephonyManager to check if device can send SMS
public boolean isSimExists() {
TelephonyManager telephonyManager = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
int SIM_STATE = telephonyManager.getSimState();

if (SIM_STATE == TelephonyManager.SIM_STATE_READY)
return true;
else {
// we can inform user about sim state
switch (SIM_STATE) {
case TelephonyManager.SIM_STATE_ABSENT:
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
case TelephonyManager.SIM_STATE_UNKNOWN:
break;
}
return false;
}
}
Option 1

Sending SMS by invoking Built-in SMS application

To send SMS using Intent object, we need to write the code like as shown below.
String phone = "+38091234567";
String message = "Hello";

Intent sendIntent = new Intent(Intent.ACTION_VIEW);


sendIntent.putExtra("address", phone);
sendIntent.putExtra("sms_body", message);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Android has built-in support to add phone number and text message to send an
SMS as follows
String phones = "+38091234567;+38091234568";

smsIntent.putExtra("address", phones);
smsIntent.putExtra("sms_body", message);

Here address and sms_body are case sensitive and should be specified in small
characters only. You can specify more than one number in single string but
separated by semi-colon (;).

Option 2

Sending SMS using SmsManager API


To send SMS programmatically in Android, we need to get an instance of the
SmsManager class using the static getDefault() method.
String phone = "+38091234567";
String message = "Hello";

try {
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(MobileNumber, null, message, null, null);
Toast.makeText(MainActivity.this, "SMS Sent Successfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try again",
Toast.LENGTH_SHORT).show();
}

The first argument passed to sendTextMessage() is the destination address to


which the message has to be sent and the second argument is the SMSC address
(it’s also like a phone number generally) to which if you pass null, the default
service center of the device’s carrier will be used. Third argument is the text
message to be sent in the SMS. The fourth and fifth arguments if not null must be
pending intents performing broadcasts when the message is successfully sent (or
failed) and delivered to the recipient.

activity_main.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="Mobile No" />
<EditText
android:id="@+id/mblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>

<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/msgTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Send SMS" />
</LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

private EditText txtMobile;


private EditText txtMessage;
private Button btnSms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMobile = (EditText)findViewById(R.id.mblTxt);
txtMessage = (EditText)findViewById(R.id.msgTxt);
btnSms = (Button)findViewById(R.id.btnSend);
btnSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(txtMobile.getText().toString(),null,txtMessag
e.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS Sent Successfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try
again", Toast.LENGTH_SHORT).show();
}
}
});
}
}

AndroidManifest.xml

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

Android Send Email

Before starting Email Activity, You must know Email functionality with intent,
Intent is carrying data from one component to another component with-in the
application or outside the application.
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. In this example, we are going to send an email from our
app by using an Intent object that launches existing email clients.
Following section explains different parts of our Intent object required to send an
email.

Intent Object - Action to send Email


You will use ACTION_SEND action to launch an email client installed on your
Android device. Following is simple 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.

6 EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to 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.

setType - We use this property to set the MIME type of data that we want to send.
Here we used “message/rfc822” and other MIME types are “text/plain” and
“image/jpg”.

Android Send Email Example

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send"
android:id="@+id/btnSend"/>
</LinearLayout>
Now open our main activity file MainActivity.java from
\src\main\java\com.tutlane.sendmailexample path and write the code like as
shown below
MainActivity.java

package com.tutlane.sendmailexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

private EditText eTo;


private EditText eSubject;
private EditText eMsg;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eTo = (EditText)findViewById(R.id.txtTo);
eSubject = (EditText)findViewById(R.id.txtSub);
eMsg = (EditText)findViewById(R.id.txtMsg);
btn = (Button)findViewById(R.id.btnSend);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, new
String[]{eTo.getText().toString()});
it.putExtra(Intent.EXTRA_SUBJECT,eSubject.getText().toString());
it.putExtra(Intent.EXTRA_TEXT,eMsg.getText());
it.setType("message/rfc822");
startActivity(Intent.createChooser(it,"Choose Mail App"));
}
});
}
}
If you observe above code we used multiple components to send email, those are

it - Our local implicit intent

ACTION_SEND - It’s an activity action that specifies that we are sending some
data.

putExtra - we use this putExtra() method to add extra information to our Intent.
Here we can add the following things.
 EXTRA_EMAIL - It’s an array of email addresses

 EXTRA_SUBJECT - The subject of the email that we want to send

 EXTRA_TEXT - The body of the email

setType - We use this property to set the MIME type of data that we want to send.
Here we used “message/rfc822” and other MIME types are “text/plain” and
“image/jpg”.

We need to add MIME type in our android manifest file for that open android
manifest file (AndroidManifest.xml) and write the code like as shown below
AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.sendmailexample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>
</activity>
</application>
</manifest>

If you observe above AndroidManifest.xml file we added following extra fields


of Intent filters.
action - we use this property to define that the activity can perform SEND action.

category - we included the DEFAULT category for this activity to be able to


receive implicit intents.

data - the type of data the activity can send.

Android - Location Based Services

By using Google Maps Android API we can integrate google maps in android
applications to show the location details on map based on our requirements.

To use google maps in our android applications we need to install Google Play
Services SDK in our Android Studio because google made Google Mas API as a
part of Google Play Services SDK.

To install Google Play Services, open Android Studio à Go to Tools menu à


Android à click SDK Manager, then new window will open in that select SDK
Tools tab à Select Google Play Services à click OK like as shown below.
Once we are done with Google Play Services installation in android studio, now
we will see how to integrate google map in android app with examples.

Android Google Maps API Example

Following is the example of adding or integrating a google map in android


application.

Create a new android application using android studio and give names as
GoogleMapExample like as shown below.
Now we need to select the form factors which we need for our app. In case if
you're not sure what you need, just select Phone and Tablet and then click Next
like as shown below.
Now select the Google Maps Activity in 'Add an activity to Mobile' dialog and
click Next like as shown below.

Customize the activity by entering activity name, layout name and title as
prompted. In case if default values are fine, then click Finish like as shown below.
The Google Maps API Key:

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:

Step 1: Open Google developer console and signin with your gmail account:
https://console.developers.google.com/project
Step 2: Now create new project. You can create new project by clicking on the
Create Project button and give name to your project.

Step 3: Now click on APIs & Services and open Dashboard from it.

Step 4: In this open Enable APIS AND SERICES.

Step 5: Now open Google Map Android API.

Step 6: Now enable the Google Maps Android API.


Step 6: Now go to Credentials

Step 7: Here click on Create credentials and choose API key

Step 8: Now API your API key will be generated. Copy it and save it somewhere
as we will need it when implementing Google Map in our Android project.
Android Google Map
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.

Syntax of different types of map


1. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
2. googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
3. googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
4. googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Methods of Google map


Google map API provides several methods that help to customize Google map.
These methods are as following:

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 update) This method moves the map

according to the update with an

animation.

clear() This method removes everything

from the map.

getMyLocation() This method returns the

currently displayed user

location.

moveCamera(CameraUpdate update) This method reposition the

camera according to the

instructions defined in the

update.

setTrafficEnabled(boolean enabled) This method set the traffic layer


on or off.

snapshot(GoogleMap.SnapshotReadyCallback This method takes a snapshot of

callback) the map.

stopAnimation() This method stops the camera

animation if there is any

progress.

Callback methods in Google Map

1. OnMapRreadyCallback: This callback interface invokes when it instance


is set on MapFragment object.

The onMapReady(GoogleMap) method of OnMapReadyCallback interface


is called when the map is ready to used.
In the onMapReady(GoogleMap) method we can add markers, listeners and
other attributes.
@Override
public void onMapReady(GoogleMap googleMap) { }

. LocationListener: This interface is used to receive notification when the


device location has changed. The abstract method of LocationListener
onLocationChanged(Location) is called when the location has changed.

@Override
public void onLocationChanged(Location location) { }
. GoogleApiClient.ConnectionCallbacks: This interface provide callbacks
methods onConnected(Bundle) and onConnectionSuspended(int) which are called
when the device is to connected and disconnected.
. GoogleApiClient.OnConnectionFailedListener: This interface provide
callbacks method onConnectionFailed(ConnectionResult) which is called when
there was an error in connecting the device to the service.

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}

The setMyLocationEnabled() method of GoogleMap is used to enable location


layer, which allows device to interact with current location.
Google Play Services

Activity_maps.xml

Add the following fragment code in ActivityMain.xml for adding Google map to
your activity
By default, the XML file (activity_maps.xml) that defines the app's layout is at
res/layout/ contains the following code.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tutlane.googlemapexample.MapsActivity" />

SupportMapFragment

A Map component in an app. This fragment is the simplest way to place a map in
an application. It's a wrapper around a view of a map to automatically handle the
necessary life cycle needs. Being a fragment, this component can be added to an
activity's layout file simply with the XML below.

<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

A GoogleMap must be acquired using getMapAsync(OnMapReadyCallback). This


class automatically initializes the maps system and the view.

Syntax:
getMapAsync(OnMapReadyCallback callback)
Sets a callback object which will be triggered when the GoogleMap instance is
ready to be used.

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

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.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to
implement in your activity class −
Sr.No. Callback Methods & Description

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.

You should create the location client in onCreate() method of your activity class,
then connect it in onStart(), so that Location Services maintains the current
location while your activity is fully visible. You should disconnect the client
in onStop() method, so that when your app is not visible, Location Services is not
maintaining the current location. This helps in saving battery power up-to a large
extent.

Request Runtime Permission

Android device having Android 6.0 (Marshmallow) or later are required some
permission at runtime to access device functionality.

In the above MapsActivity.java file we added a runtime


permission Manifest.permission.ACCESS_FINE_LOCATION which request to
access device location. The runtime permission is checked
using checkSelfPermission() method and
return PackageManager.PERMISSION_GRANTED or PackageManager.PERMISS
ION_DENIED. If permission granted than app proceeds for operation.
Required Permission in AndroidManifest.xml

Add the following user-permission in AndroidManifest.xml file.

1. <uses-
permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-
permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

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


4.

ACCESS_COARSE_LOCATION: It provides location accuracy within a city


block. Allows the API to use WiFi or mobile cell data (or both) to determine the
device's location.
<uses-permission
android:name=”android.permission.ACCESS_COARSE_LOCATION”/>
ACCESS_FINE_LOCATION: It provides a more accurate location. To do this,
it needs to do some heavy lifting so it’s recommended to use this only when we
need an accurate location.
Allows the API to determine as precise a location as possible from the available
location providers, including the Global Positioning System (GPS) as well as WiFi
and mobile cell data.

<uses-permission
android:name=”android.permission.ACCESS_FINE_LOCATION” />
In case the app needs to access the user’s location while the app is running in
the background, we need to add the following permission along with the above
ones:
<uses-permission
android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />
We need to add all these permissions in the AndroidManifest.xml. To access this
file, select your project view as Android and click on:
app->manifests->AndroidManifest.xml.
AndroidManifest.xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getuserlocation">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.GetUserLocation">
<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>

Add a marker

Markers identify locations on the map.It indicate single locations on the map.We
can place a maker with some text over it displaying your location on map.It can be
done by addMarker() method

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.

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

Geocoding and reverse geocoding

Searching location in Google Map API is done through Geocoder class. Geocoder
class is used to handle geocoding and reverse geocoding.

Geocoding is a process in which street address is converted into a coordinate


(latitude,longitude). Reverse geocoding is a process in which a coordinate
(latitude,longitude) is converted into an address.

public final class Geocoder


extends Object

java.lang.Object
↳ android.location.Geocoder
Public constructors
Geocoder(Context context)

Constructs a Geocoder localized for the default locale.


Geocoder(Context context, Locale locale)

Constructs a Geocoder localized for the given locale.


Methods of Geocoder class

1. List<Address> getFromLocation(double latitude, double longitude, int


maxResults): This method returns an array of Address which specifies the
surrounding latitude and longitude.
2. List<Address> getFromLocationName(String location, int results,
double leftLatitude, double leftLongitude, double rightLatitude, double
rightLongitude): This method returns an array of Address which describes
the given location such as place, an address, etc.
3. List<Address> getFromLocationName(String location, int results): This
method returns an array of Address which describes te given location such
as place, an address, etc.
4. static boolean isPresent(): This method returns true if the methods
getFromLocation() and getFromLocationName() are implemented.

Syntax-

Public methods
List<Addre getFromLocation(double latitude, double longitude, int maxResults)
ss>
This method was deprecated in API level 33. Use getFromLocation(double, double, int,
android.location.Geocoder.GeocodeListener) instead to avoid blocking a thread
waiting for results.
void getFromLocation(double latitude, double longitude, int
maxResults, Geocoder.GeocodeListener listener)

Provides an array of Addresses that attempt to describe the area immediately


surrounding the given latitude and longitude.
List<Addre getFromLocationName(String locationName, int maxResults, double
ss> lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double
upperRightLongitude)

This method was deprecated in API level 33.


Use getFromLocationName(java.lang.String, int, double, double, double, double,
android.location.Geocoder.GeocodeListener) instead to avoid blocking a thread
waiting for results.
void getFromLocationName(String locationName, int maxResults, double
lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double
upperRightLongitude, Geocoder.GeocodeListener listener)

Returns an array of Addresses that attempt to describe the named location, which may
be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre
Parkway, Mountain View, CA", an airport code such as "SFO", and so forth.
void getFromLocationName(String locationName, int
maxResults, Geocoder.GeocodeListener listener)

Provides an array of Addresses that attempt to describe the named location, which may
be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre
Parkway, Mountain View, CA", an airport code such as "SFO", and so forth.
List<Addre getFromLocationName(String locationName, int maxResults)
ss>
This method was deprecated in API level 33.
Use getFromLocationName(java.lang.String, int,
android.location.Geocoder.GeocodeListener) instead to avoid blocking a thread
waiting for results.
static isPresent()
boolean
Returns true if there is a geocoder implementation present that may return results.

Let's see the code which convert location name into coordinate.

1. List<Address> addressList = geocoder.getFromLocationName(location, 1);


2. Address address = addressList.get(0);
3. LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

1. Write a program to locate user’s current location.


Java
package com.example.maps1;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.tasks.OnSuccessListener;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback {
private GoogleMap mMap;
Geocoder geocoder;
public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,
@NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions,grantResults);
if (requestCode == 101) {
// Checking whether user granted the permission or not.
if (grantResults.length > 0 && grantResults[0] ==PackageManager.PERMISSION_GRANTED)
{
// Showing the toast message
Toast.makeText(this, "Location Permission Granted",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "LocationCamera Permission Denied",Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[]
{ Manifest.permission.ACCESS_FINE_LOCATION }, 101);
return;
} //Enable Current Location
mMap.setMyLocationEnabled(true);
//settings
UiSettings mapUI= googleMap.getUiSettings();
mapUI.setAllGesturesEnabled(true);
mapUI.setMyLocationButtonEnabled(true);
mapUI.setCompassEnabled(true);
}
}
Used Methods are-
Settings for the user interface of a GoogleMap. To obtain this interface,
call GoogleMap.getUiSettings().
UiSettings mapUI= googleMap.getUiSettings();

public void setMyLocationButtonEnabled (boolean enabled)

Enables or disables the my-location button. The my-location button causes the
camera to move such that the user's location is in the center of the map. If the
button is enabled, it is only shown when the my-location layer is enabled.

By default, the my-location button is enabled (and hence shown when the my-
location layer is enabled).
Parameters
enabled true to enable the my-location button; false to disable the my-location button.
public void setAllGesturesEnabled (boolean enabled)

Sets the preference for whether all gestures should be enabled or disabled. If
enabled, all gestures are available; otherwise, all gestures are disabled. This doesn't
restrict users from tapping any on screen buttons to move the camera (e.g.,
compass or zoom controls), nor does it restrict programmatic movements and
animation.
Parameters
true to enable all gestures; false to disable all gestures.
enabled

public void setCompassEnabled (boolean enabled)

Enables or disables the compass. The compass is an icon on the map that indicates
the direction of north on the map. If enabled, it is only shown when the camera is
tilted or rotated away from its default orientation (tilt of 0 and a bearing of 0).
When a user clicks the compass, the camera orients itself to its default orientation
and fades away shortly after. If disabled, the compass will never be displayed.

By default, the compass is enabled (and hence shown when the camera is not in the
default orientation).
Parameters
enabled true to enable the compass; false to disable the compass.

2.Write a program to locate user’s current location.

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

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

<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javapapers.android.geolocationfinder"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppBaseTheme" >
<activity
android:name="com.javapapers.android.geolocationfinder.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
</application>
</manifest>

Android Output
Que – Write a program to draw a route between two locations.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:layout_margin="20dp">
<EditText
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_source"
android:hint="Enter Source Location"
android:padding="13dp"
android:background="@drawable/input"/>
<EditText
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_destination"
android:hint="Enter Destination Location"
android:padding="13dp"
android:background="@drawable/input"/>
<Button
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/track"
android:text="Draw Route"/>
</LinearLayout>

MainActivity.java
package co6i.micro.project.shantanu.practical32;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText source, destination;
Button track;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
source = findViewById(R.id.et_source);
destination = findViewById(R.id.et_destination);
track = findViewById(R.id.track);
track.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String sSource = source.getText().toString();
String sDestination = destination.getText().toString();
if(sSource.equals("") && sDestination.equals("")){
Toast.makeText(MainActivity.this,"Enter Both
Location",Toast.LENGTH_SHORT).show();
}
else{
DisplayTrack(sSource,sDestination);
}
}
});
}
private void DisplayTrack(String sSource, String sDestination) {
try {
Uri uri =
Uri.parse("https://www.google.co.in/maps/dir/"+sSource+"/"+sDestination);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setPackage("com.google.android.apps.maps");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// This Flag Only Starts an Activity in a new Task If it's not previously started
startActivity(intent);
}
catch (ActivityNotFoundException e){
Uri uri =
Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps
.maps");
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
OUTPUT
Android Security Model

The Android operating system differentiates three types of permissions: normal


permissions, signature permissions and dangerous permissions.

Normal permissions grant access to data and resources outside of the application
sandbox which have very little risk to compromise user’s data or other applications
on the system. Normal permissions declared in the application’s manifest are
automatically granted upon installing the application on the device. Users do not
need to grant these permissions and cannot revoke them.
The android.permission.INTERNET permission, allowing the application to access
the internet, is an example of normal permission.

Permissions include the following permissions:


1. ACCESS_LOCATION_EXTRA_COMMANDS
2. ACCESS_NETWORK_STATE
3. CHANGE_NETWORK_STATE
4. ACCESS_WIFI_STATE
5. CHANGE_WIFI_STATE
6. CHANGE_WIFI_MULTICAST_STATE
7. BLUETOOTH
8. BLUETOOTH_ADMIN
9. INTERNET
10.SET_ALARM
11.SET_WALLPAPER
12.VIBRATE
13.WAKE_LOCK

Signature permissions grant access to custom permissions declared by an


application signed with the same certificate as the requesting application. These
permissions are granted automatically by the system upon installation. Users do
not need to grant those permissions and cannot revoke them.
Signature permissions are as follows:
1. BIND_ACCESSIBILITY_SERVICE
2. BIND_AUTOFILL_SERVICE
3. BIND_CARRIER_SERVICE
4. BIND_DEVICE_ADMIN
5. BIND_INPUT_METHOD
6. BIND_NFC_SERVICE
7. BIND_TV_INPUT
8. BIND_WALLPAPER
9. READ_VOICEMAIL
10.WRITE_SETTINGS
11.WRITE_VOICEMAIL

Dangerous permissions grant access to data and resources outside of the


application sandbox which could have an impact on the user’s data, the system or
other applications. If an application requests a dangerous permission in its
manifest, the user will have to explicitly grant the permission to the application. On
devices running Android 6.0 (API level 23) or above, the application has to request
the permission to the user at runtime through a prompt. The user can then choose
to allow or deny the permission. The user can later revoke any granted permissions
in the settings of the application, in the device settings. On devices running
Android 5.1.1 (API level 22) and older, the system will ask the user to grant all the
dangerous permissions during installation. If the user accepts, all the permissions
will be given to the application. Otherwise, the installation of the application will
be cancelled. The android.permission.ACCESS_FINE_LOCATION permission,
allowing the application to access the precise location of the device, is an example
of a dangerous permission.
Some of the Dangerous permissions are as follows:
1. READ_CALENDAR
2. WRITE_CALENDAR
3. CAMERA
4. READ_CALL_LOG
5. WRITE_CALL_LOG
6. READ_CONTACTS
7. WRITE_CONTACTS
8. GET_ACCOUNTS
9. ACCESS_FINE_LOCATION
10.ACCESS_COARSE_LOCATION
11.SEND_SMS
12.RECEIVE_SMS

Android Security Features


Below are the security features provided by Android to make the Android devices
you develop as secure as possible.

App sandbox

The Android platform takes advantage of the Linux user-based protection to


identify and isolate app resources. To do this, Android assigns a unique user ID
(UID) to each Android app and runs it in its own process. Android uses this UID to
set up a kernel-level App Sandbox.

App signing

App signing allows developers to identify the author of the app and to update their
app without creating complicated interfaces and permissions. Every app that runs
on the Android platform must be signed by the developer.

Authentication

Android uses the concept of user-authentication-gated cryptographic keys that


requires cryptographic key storage and service provider and user authenticators.

On devices with a fingerprint sensor, users can enroll one or more fingerprints and
use those fingerprints to unlock the device and perform other tasks. The Gatekeeper
subsystem performs device pattern/password authentication in a Trusted Execution
Environment (TEE).
Android 9 and higher includes Protected Confirmation, which gives users a way to
formally confirm critical transactions, such as payments.

Biometrics

Android 9 and higher includes a BiometricPrompt API that app developers can use
to integrate biometric authentication into their apps in a device- and modality-
agnostic fashion. Only strong biometrics can integrate with BiometricPrompt.

Encryption

Once a device is encrypted, all user-created data is automatically encrypted before


committing it to disk and all reads automatically decrypt data before returning it to
the calling process. Encryption ensures that even if an unauthorized party tries to
access the data, they won’t be able to read it.

Keystore

Android offers a hardware-backed Keystore that provides key generation, import


and export of asymmetric keys, import of raw symmetric keys, asymmetric
encryption and decryption with appropriate padding modes, and more.

Security-Enhanced Linux

As part of the Android security model, Android uses Security-Enhanced Linux


(SELinux) to enforce mandatory access control (MAC) over all processes, even
processes running with root/superuser privileges (Linux capabilities).
Trusty Trusted Execution Environment (TEE)

Trusty is a secure Operating System (OS) that provides a Trusted Execution


Environment (TEE) for Android. The Trusty OS runs on the same processor as the
Android OS, but Trusty is isolated from the rest of the system by both hardware and
software.

Verified Boot

Verified Boot strives to ensure all executed code comes from a trusted source
(usually device OEMs), rather than from an attacker or corruption. It establishes a
full chain of trust, starting from a hardware-protected root of trust to the bootloader,
to the boot partition and other verified partitions.
Permissions to be granted at install time in
Android 5.1.1 and older
Permissions to be granted at runtime in Android
6.0 and above

Types of Permissions
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 canceled.
1. 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 permission again.
So, now the permissions are requested at runtime. In this article, we will discuss
how to request permissions in an Android Application at run time.
Application Deployment

Application Signing

Application signing allows developers to identify the author of the application and
to update their application without creating complicated interfaces and
permissions. Every application that is run on the Android platform must be signed
by the developer. Applications that attempt to install without being signed will be
rejected by either Google Play or the package installer on the Android device.

How to Generate Signed Apk in Android Studio?


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.
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 your app
Android application publishing is a process that makes your Android applications
available to users. Infect, publishing is the last phase of the Android application
development process

How do I launch an application in android app store?

The simple procedures are here

1. Purchase your Google Developer account from Google Developers (cost $25)
2. Be ready with your Apk file and make sure it is compatible with all devices and
Google Play Store policies as well.
3. After the successful purchase of your account, go here Google Play Developer
Console
4. On the right side, you can see an option like "Add new Application".
5. Upload the Apk file, fill the forms and add the screenshots.
6. Finally click Publish App
7. The team will review your application and make it live within 24 hours time.

Developer Console

The Google Play Console is the back-end interface that Android developers

and publishers can use to upload new apps, manage existing ones, and

monitor performance.

Some of the things you can do from the Google Play Console include:

 Upload and publish apps


 Create/modify store listings
 View sales and statistics
 Manage different versions of your app
 View ratings and reviews (and respond)
 View crash reports

Google Play Developer Console is the platform that Google provides for Google
Play and Android developers to publish – and of particular interest to ASO teams –
to monitor their app’s performance in the Google Play store. As Google explains,
by using the platform it’s possible to: “Publish your apps and games with the
Google Play Console and grow your business on Google Play. Benefit from
features that help you improve your app’s quality, engage your audience, earn
revenue, and more.”

Why the Google Play Developer Console is Important

The Google Play console allows app developers and marketers to better understand
how their apps are performing in terms of growth, technical performance such as
crashes or display issues, and financials. The console offers acquisition reports and
detailed analysis which can help app devs / marketers find out how well an app is
really performing.

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