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

Mad Chapter - 6 Notes

The document discusses how to send SMS and email from an Android application using SMSManager API, Intents, and other methods. It provides code samples for sending SMS by passing the phone number and message to the SMSManager's sendTextMessage method or by using an Intent. It also discusses how to send an email by creating an Intent with ACTION_SEND and adding extras for TO, SUBJECT, TEXT etc.

Uploaded by

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

Mad Chapter - 6 Notes

The document discusses how to send SMS and email from an Android application using SMSManager API, Intents, and other methods. It provides code samples for sending SMS by passing the phone number and message to the SMSManager's sendTextMessage method or by using an Intent. It also discusses how to send an email by creating an Intent with ACTION_SEND and adding extras for TO, SUBJECT, TEXT etc.

Uploaded by

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

Chapter -6 Security and Application Development

SMS Telephony
In android, we can send SMS from our android application in two ways either by using
SMSManager API or Intents based on our requirements.
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 a built-in SMS app to send SMS
from our application.

Android Send SMS using SMSManager API


In android, to send SMS using SMSManager API we need to write the code like as shown
below.

SmsManager smgr = SmsManager.getDefault();


smgr.sendTextMessage(MobileNumber,null,Message,null,null);
SMSManager API required SEND_SMS permission in our android manifest to send SMS.
Following is the code snippet to set SEND_SMS permissions in manifest file.

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

Android Send SMS using Intent


In android, Intent is a messaging object which is used to request an action from another app
component such as activities, services, broadcast receivers, and content providers.
To send SMS using the Intent object, we need to write the code like as shown below.
Intent sInt = new Intent(Intent.ACTION_VIEW);
sInt.putExtra("address", new String[]{txtMobile.getText().toString()});
sInt.putExtra("sms_body",txtMessage.getText().toString());
sInt.setType("vnd.android-dir/mms-sms");
Even for Intent, it required a SEND_SMS permission in our android manifest to send SMS.
Following is the code snippet to set SEND_SMS permissions in manifest file.

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

Apart from the above method, there are few other important functions available in SmsManager
class. These methods are listed below −

Sr.No Method & Description


.
1
ArrayList<String> divideMessage(String text)
This method divides a message text into several fragments, none bigger than the maximum
SMS message size.

2
static SmsManager getDefault()
This method is used to get the default instance of the SmsManager

3
void sendDataMessage(String destinationAddress, String scAddress, short
destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)
This method is used to send a data based SMS to a specific application port.

4
void sendMultipartTextMessage(String destinationAddress, String scAddress,
ArrayList<String> parts, ArrayList<PendingIntent> sentIntents,
ArrayList<PendingIntent> deliveryIntents)
Send a multi-part text based SMS.

5
void sendTextMessage(String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent)
Send a text based SMS.

Sending Email
Email is messages distributed by electronic means from one system user to one or more
recipients via a network.
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.

Here is an example showing you how to assign extra data to your intent −
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]
{"Recipient"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT , "Message Body");
The out-put of above code is as below shown an image

package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


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

Button startBtn = (Button) findViewById(R.id.sendEmail);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendEmail();
}
});
}
protected void sendEmail() {
Log.i("Send email", "");
String[] TO = {""};
String[] CC = {""};
Intent emailIntent = new Intent(Intent.ACTION_SEND);

emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes
here");

try {
startActivity(Intent.createChooser(emailIntent, "Send
mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There is no email
client installed.", Toast.LENGTH_SHORT).show();
}
}
}

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

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending Mail Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:id="@+id/sendEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/compose_email"/>

</LinearLayout>

strings.xml −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="compose_email">Compose Email</string>
</resources>

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

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

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
I assume you have connected your actual Android Mobile device with your computer. To run
the app from Android Studio, open one of your project's activity files and click Run icon from
the toolbar. Before starting your application, Android studio installer will display following
window to select an option where you want to run your Android application.Select your mobile
device as an option and then check your mobile device which will display following screen −
Now use Compose Email button to list down all the installed email clients. From the list, you
can choose one of email clients to send your email. I'm going to use Gmail client to send my
email which will have all the provided defaults fields available as shown below. Here From: will
be default email ID you have registered for your Android device.
You can modify either of the given default fields and finally use send email button to send your
email to the mentioned recipients.

Location Based Services


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.
This tutorial shows you how to use Location Services in your APP to get the current location,
get periodic location updates, look up addresses etc.

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.

Get the Updated Location


If you are willing to have location updates, then apart from above mentioned interfaces, you will
need to implement LocationListener interface as well. This interface provide following callback
method, which you need to implement in your activity class −
Sr.No Callback Method & Description
.

1
abstract void onLocationChanged(Location location)
This callback method is used for receiving notifications from the LocationClient when the
location has changed.

Location Quality of Service


The LocationRequest object is used to request a quality of service (QoS) for location updates
from the LocationClient. There are following useful setter methods which you can use to handle
QoS. There are equivalent getter methods available which you can check in Android official
documentation.

Sr.No Method & Description


.

1
setExpirationDuration(long millis)
Set the duration of this request, in milliseconds.

2
setExpirationTime(long millis)
Set the request expiration time, in millisecond since boot.

3
setFastestInterval(long millis)
Explicitly set the fastest interval for location updates, in milliseconds.

4
setInterval(long millis)
Set the desired interval for active location updates, in milliseconds.

5
setNumUpdates(int numUpdates)
Set the number of location updates.

6
setPriority(int priority)
Set the priority of the request.

Now for example, if your application wants high accuracy location it should create a location
request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5
seconds. You can also use bigger interval and/or other priorities like
PRIORITY_LOW_POWER for to request "city" level accuracy or
PRIORITY_BALANCED_POWER_ACCURACY for "block" level accuracy.
Activities should strongly consider removing all location request when entering the background
(for example at onPause()), or at least swap the request to a larger interval and lower quality to
save power consumption.

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.

Example
Following example shows you in practical how to to use Location Services in your app to get the
current location and its equivalent addresses etc.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.
Create Android Application
Step Description

1 You will use Android studio IDE to create an Android application and name it as under a
package com.example.tutorialspoint7.myapplication.

2 add src/GPSTracker.java file and add required code.

3 Modify src/MainActivity.java file and add required code as shown below to take care of getting
current location and its equivalent address.

4 Modify layout XML file res/layout/activity_main.xml to add all GUI components which include
three buttons and two text views to show location/address.

5 Modify res/values/strings.xml to define required constant values

6 Modify AndroidManifest.xml as shown below


7 Run the application to launch Android emulator and verify the result of the changes done in the
application.

Following is the content of the modified main activity file MainActivity.java.


package com.example.tutorialspoint7.myapplication;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

// GPSTracker class
GPSTracker gps;

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

try {
if (ActivityCompat.checkSelfPermission(this,
mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]


{mPermission},
REQUEST_CODE_PERMISSION);

// If any permission above not allowed by user, this


condition will
execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}

btnShowLocation = (Button) findViewById(R.id.button);

// show location button click event


btnShowLocation.setOnClickListener(new
View.OnClickListener() {

@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);

// check if GPS enabled


if(gps.canGetLocation()){

double latitude = gps.getLatitude();


double longitude = gps.getLongitude();

// \n is for new line


Toast.makeText(getApplicationContext(), "Your
Location is - \nLat: "
+ latitude + "\nLong: " + longitude,
Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}

}
});
}
}

Following is the content of the modified main activity file GPSTracker.java.


package com.example.tutorialspoint7.myapplication;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements


LocationListener {

private final Context mContext;


// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status


boolean isNetworkEnabled = false;

// flag for GPS status


boolean canGetLocation = false;

Location location; // location


double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES =
10; // 10 meters

// The minimum time between updates in milliseconds


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
// 1 minute

// Declaring a Location Manager


protected LocationManager locationManager;

public GPSTracker(Context context) {


this.mContext = context;
getLocation();
}

public Location getLocation() {


try {
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);

// getting GPS status


isGPSEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status


isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {


// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWOR
K_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

// if GPS Enabled get lat/long using GPS Services


if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("GPS Enabled", "GPS Enabled");


if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS
_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
}

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */

public void stopUsingGPS(){


if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */

public double getLatitude(){


if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */

public double getLongitude(){


if(location != null){
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */

public boolean canGetLocation() {


return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */

public void showSettingsAlert(){


AlertDialog.Builder alertDialog = new
AlertDialog.Builder(mContext);

// Setting Dialog Title


alertDialog.setTitle("GPS is settings");

// Setting Dialog Message


alertDialog.setMessage("GPS is not enabled. Do you want to
go to settings menu?");

// On pressing Settings button


alertDialog.setPositiveButton("Settings", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button


alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message


alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

Following will be the content of res/layout/activity_main.xml file −


<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android =
"http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:orientation = "vertical" >
<Button
android:id = "@+id/button"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "getlocation"/>

</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants −


<?xml version = "1.0" encoding = "utf-8"?>
<resources>
<string name = "app_name">Tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml −


<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android =
"http://schemas.android.com/apk/res/android"
package = "com.example.tutorialspoint7.myapplication">
<uses-permission android:name =
"android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name = "android.permission.INTERNET"
/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">

<activity android:name = ".MainActivity">


<intent-filter>
<action android:name = "android.intent.action.MAIN"
/>

<category android:name =
"android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Let's try to run your application. I assume that, you have connected your actual Android Mobile
device with your computer. To run the app from Android Studio, open one of your project's
activity files and click Run icon from the toolbar. Before starting your application, Android
studio installer will display following window to select an option where you want to run your
Android application.
Now to see location select Get Location Button which will display location information as
follows −
Google Maps
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


The next thing you need to do is to add some permissions along with the Google Map API key
in the AndroidManifest.XML file. Its syntax is given below −
<!--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);

Enable/Disable zoom
You can also enable or disable the zoom gestures in the map by calling
the setZoomControlsEnabled(boolean) method. Its syntax is given below −
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Apart from these customization, there are other methods available in the GoogleMap class , that
helps you more customize the map. They are listed below −

Sr.No Method & description

1 addCircle(CircleOptions options)
This method add a circle to the map

2 addPolygon(PolygonOptions options)
This method add a polygon to the map

3 addTileOverlay(TileOverlayOptions options)
This method add tile overlay to the map

4 animateCamera(CameraUpdate update)
This method Moves the map according to the update with an animation

5 clear()
This method removes everything from the map.

6 getMyLocation()
This method returns the currently displayed user location.

7 moveCamera(CameraUpdate update)
This method repositions the camera according to the instructions defined in the update
8 setTrafficEnabled(boolean enabled)
This method Toggles the traffic layer on or off.

9 snapshot(GoogleMap.SnapshotReadyCallback callback)
This method Takes a snapshot of the map

10 stopAnimation()
This method stops the camera animation if there is one in progress

Example
Here is an example demonstrating the use of GoogleMap class. It creates a basic M application
that allows you to navigate through the map.
To experiment with this example , you can run this on an actual device or in an emulator.
Create a project with google maps activity as shown below −

It will open the following screen and copy the console url for API Key as shown below −
Copy this and paste it to your browser. It will give the following screen −

Click on continue and click on Create API Key then it will show the following screen

Here is the content of activity_main.xml.


<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.example.tutorialspoint7.myapplication.MapsActi
vity" />

Here is the content of MapActivity.java.


In the below code we have given sample latitude and longitude details

package com.example.tutorialspoint7.myapplication;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

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.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements


OnMapReadyCallback {

private GoogleMap mMap;

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

/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be
used.
* This is where we can add markers or lines, add listeners
or move the camera.
* In this case, we just add a marker near Sydney,
Australia.
* If Google Play services is not installed on the device.
* This method will only be triggered once the user has
installed
Google Play services and returned to the app.
*/

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng TutorialsPoint = new LatLng(21, 57);
mMap.addMarker(new

MarkerOptions().position(TutorialsPoint).title("Tutorialspoint.co
m"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint));
}
}

Following is the content of AndroidManifest.xml file.


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

<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not
required to use
Google Maps Android API v2, but you must specify either
coarse or fine
location permissions for the 'MyLocation' functionality.
-->

<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<!--
The API key for Google Maps-based APIs is defined as a
string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key
used to sign the APK.
You need a different API key for each encryption key,
including the release key
that is used to sign the APK for publishing.
You can define the keys for the debug and
release targets in src/debug/ and src/release/.
-->

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes"
/>

<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Output should be like this −

Android security model


Android is a multi-process system, in which each application (and parts of the system) runs in its
own process. Most security between applications and the system is enforced at the process level
through standard Linux facilities, such as user and group IDs that are assigned to applications.
Additional finer-grained security features are provided through a “permission” mechanism that
enforces restrictions on the specific operations that a particular process can perform, and per-URI
permissions for granting ad-hoc access to specific pieces of data.
The Android security model is primarily based on a sandbox and permission mechanism. Each
application is running in a specific Dalvik virtual machine with a unique user ID assigned to it,
which means the application code runs in isolation from the code of all others applications. As a
consequence, one application has not granted access to other applications’ files.

Android application has been signed with a certificate with a private key Know the owner of the
application is unique. This allows the author of The application will be identified if needed. When
an application is installed in The phone is assigned a user ID, thus avoiding it from affecting it
Other applications by creating a sandbox for it. This user ID is permanent on which devices and
applications with the same user ID are allowed to run in a single process. This is a way to ensure
that a malicious application has Cannot access / compromise the data of the genuine application.
It is mandatory for an application to list all the resources it will Access during installation. Terms
are required of an application, in The installation process should be user-based or interactive
Check with the signature of the application.
The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as certain
system features (such as camera and internet). Depending on the feature, the system might grant
the permission automatically or might prompt the user to approve the request.

Permissions are divided into several protection levels. The protection level affects whether
runtime permission requests are required. There are three protection levels that affect third-party
apps: normal, signature, and dangerous permissions.
Normal permissions cover areas where your app needs to access data or resources outside the
app’s sandbox, but where there’s very little risk to the user’s privacy or the operation of other
apps. For example, permission to set the time zone is a normal permission. If an app declares in
its manifest that it needs a normal permission, the system automatically grants the app that
permission at install time. The system doesn’t prompt the user to grant normal permissions, and
users cannot revoke these permissions.
Signature permissions: The system grants these app permissions at install time, but only when the
app that attempts to use a permission is signed by the same certificate as the app that defines the
permission.
Dangerous permissions cover areas where the app wants data or resources that involve the user’s
private information, or could potentially affect the user’s stored data or the operation of other
apps. For example, the ability to read the user’s contacts is a dangerous permission. If an app
declares that it needs a dangerous permission, the user has to explicitly grant the permission to the
app. Until the user approves the permission, your app cannot provide functionality that depends
on that permission. To use a dangerous permission, your app must prompt the user to grant
permission at runtime. For more details about how the user is prompted, see Request prompt for
dangerous permission.

Android threat
However, the Android operating system also revealed some of its faults for the user may be
attacked and stolen personal information.
Some security vulnerabilities on Android:
– Leaking Information to Logs: Android provides centralized logging via the Log API, which can
displayed with the “logcat” command. While logcat is a debugging tool, applications with the
READ_LOGS permission can read these log messages. The Android documentation for this
permission indicates that “the logs can contain slightly private information about what is
happening on the device, but should never contain the user’s private information.”
– SDcard Use: Any application that has access to read or write data on the SDcard can read or
write any other application’s data on the SDcard.
– Unprotected Broadcast Receivers: Applications use broadcast receiver components to receive
intent messages. Broadcast receivers define “intent filters” to subscribe to specific event types are
public. If the receiver is not protected by a permission, a malicious application can forge
messages.
– Intent Injection Attacks: Intent messages are also used to start activity and service components.
An intent injection attack occurs if the in-tent address is derived from untrusted input.
– Wifi Sniffing: This may disrupt the data being transmitted from A device like many web sites
and applications does not have security measures strict security. The application does not encrypt
the data and therefore it can be Blocked by a listener on unsafe lines.
Security issues for smartphones running on the system Android operating system is the user does
not have the knowledge or careless installation of the software Malicious or other attacks such as
phishing. Important security issues The second is that some legitimate applications that have
vulnerabilities can be exploited.

Request App Permissions


Every Android app runs in a limited-access sandbox. If an app needs to use resources or
information outside of its own sandbox, the app has to request the appropriate permission. You
declare that your app needs a permission by listing the permission in the app manifest and then
requesting that the user approve each permission at runtime .

This page describes how to use the Android Support Library to check for and request
permissions. The Android framework provides similar methods as of Android 6.0 but using the
support library makes it easier to provide compatibility with older versions of Android.
Add permissions to the manifest
On all versions of Android, to declare that your app needs a permission, put a <uses-
permission> element in your app manifest, as a child of the top-level <manifest> element.
For example, an app that needs to access the internet would have this line in the manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">

<uses-permission android:name="android.permission.INTERNET"/>
<!-- other permissions go here -->

<application ...>
...
</application>
</manifest>

The system's behavior after you declare a permission depends on how sensitive the permission is.
Some permissions are considered "normal" so the system immediately grants them upon
installation. Other permissions are considered "dangerous" so the user must explicitly grant your
app access. For more information about the different kinds of permissions, see Protection
levels.

Check for permissions


If your app needs a dangerous permission, you must check whether you have that permission
every time you perform an operation that requires that permission. Beginning with Android 6.0
(API level 23), users can revoke permissions from any app at any time, even if the app targets a
lower API level. So even if the app used the camera yesterday, it can't assume it still has that
permission today.

To check if you have a permission, call


the ContextCompat.checkSelfPermission() method. For example, this snippet shows
how to check if the activity has permission to write to the calendar:

JAVA

if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
}

If the app has the permission, the method returns PERMISSION_GRANTED, and the app can
proceed with the operation. If the app does not have the permission, the method
returns PERMISSION_DENIED, and the app has to explicitly ask the user for permission.
Declaring and using permissions
Request permissions
When your app receives PERMISSION_DENIED from checkSelfPermission(), you need
to prompt the user for that permission. Android provides several methods you can use to request a
permission, such as requestPermissions(), as shown in the code snippet below. Calling
these methods brings up a standard Android dialog, which you cannot customize.

How this is displayed to the user depends on the device Android version as well as the target
version of your application.

Explain why the app needs permissions


In some circumstances, you want to help the user understand why your app needs a permission.
For example, if a user launches a photography app, the user probably won't be surprised that the
app asks for permission to use the camera, but the user might not understand why the app wants
access to the user's location or contacts. Before your app requests a permission, you should
consider providing an explanation to the user. Keep in mind that you don't want to overwhelm the
user with explanations; if you provide too many explanations, the user might find the app
frustrating and remove it.

One approach you might use is to provide an explanation only if the user has already denied that
permission request. Android provides a utility
method, shouldShowRequestPermissionRationale(), that returns true if the user has
previously denied the request, and returns false if a user has denied a permission and selected
the Don't ask again option in the permission request dialog, or if a device policy prohibits the
permission.

If a user keeps trying to use functionality that requires a permission, but keeps denying the
permission request, that probably means the user doesn't understand why the app needs the
permission to provide that functionality. In a situation like that, it's probably a good idea to show
an explanation.

Request to become the default handler if necessary


Some apps depend on access to sensitive user information related to call logs and SMS messages.
If you want to request the permissions specific to call logs and SMS messages and publish your
app to the Play Store, you must prompt the user to set your app as the default handler for a core
system function before requesting these runtime permissions.

Request the permissions you need


If your app doesn't already have the permission it needs, the app must call one of
the requestPermissions() methods to request the appropriate permissions. Your app passes
the permissions it wants and an integer request code that you specify to identify this permission
request. This method functions asynchronously. It returns right away, and after the user responds
to the prompt, the system calls the app's callback method with the results, passing the same
request code that the app passed to requestPermissions().
The following code checks if the app has permission to read the user's contacts. If it does not
have permission it checks if it should show an explanation for needing the permission, and if no
explanation is needed, it requests the permission:

// Here, thisActivity is the current activity


if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {

// Permission is not granted


// Should we show an explanation?
if
(ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation to the user *asynchronously* -- don't
block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
}

The prompt shown by the system describes the permission group your app needs access to, not
the specific permission.

Note: When your app calls requestPermissions(), the system shows a standard dialog box to
the user. Your app cannot configure or alter that dialog box. If you need to provide any
information or explanation to the user, you should do that before you
call requestPermissions(), as described in Explain why the app needs permissions.

Handle the permissions request response


When the user responds to your app's permission request, the system invokes your
app's onRequestPermissionsResult() method, passing it the user response. Your app has
to override that method to find out whether the permission was granted. The callback is passed
the same request code you passed to requestPermissions(). For example, if an app
requests READ_CONTACTS access it might have the following callback method:
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}

// other 'case' lines to check for other


// permissions this app might request.
}
}

The dialog box shown by the system describes the permission group your app needs access to;
it does not list the specific permission. For example, if you request
the READ_CONTACTS permission, the system dialog box just says your app needs access to the
device's contacts. The user only needs to grant permission once for each permission group. If
your app requests any other permissions in that group (that are listed in your app manifest), the
system automatically grants them. When you request the permission, the system calls
your onRequestPermissionsResult() callback method and
passes PERMISSION_GRANTED, the same way it would if the user had explicitly granted your
request through the system dialog box.

Note: Your app still needs to explicitly request every permission it needs, even if the user has
already granted another permission in the same group. In addition, the grouping of permissions
into groups may change in future Android releases. Your code should not rely on the assumption
that particular permissions are or are not in the same group.

For example, suppose you list both READ_CONTACTS and WRITE_CONTACTS in your app
manifest. If you request READ_CONTACTS and the user grants the permission, and you then
request WRITE_CONTACTS, the system immediately grants you that permission without
interacting with the user.

If the user denies a permission request, your app should take appropriate action. For example,
your app might show a dialog explaining why it could not perform the user's requested action that
needs that permission.
When the system asks the user to grant a permission, the user has the option of telling the system
not to ask for that permission again. In that case, any time an app
uses requestPermissions() to ask for that permission again, the system immediately denies
the request. The system calls your onRequestPermissionsResult() callback method and
passes PERMISSION_DENIED, the same way it would if the user had explicitly rejected your
request again. The method also returns false if a device policy prohibits the app from having that
permission. This means that when you call requestPermissions(), you cannot assume that
any direct interaction with the user has taken place.

Declare permissions by API level


To declare a permission only on devices that support runtime permissions—that is, devices
running Android 6.0 or higher—include the uses- permission-sdk-23 tag instead of
the uses-permission tag.

When using either of these tags, you can set the maxSdkVersion attribute to specify that, on
devices running a higher version, a particular permission isn't needed.

Custom permissions
Define a Custom App Permission
This document describes how app developers can use the security features provided by Android
to define their own permissions. By defining custom permissions, an app can share its resources
and capabilities with other apps.

Background
Android is a privilege-separated operating system, in which each app runs with a distinct system
identity (Linux user ID and group ID). Parts of the system are also separated into distinct
identities. Linux thereby isolates apps from each other and from the system.

Apps can expose their functionality to other apps by defining permissions which those other apps
can request. They can also define permissions which are automatically made available to any
other apps which are signed with the same certificate.

App signing
All APKs must be signed with a certificate whose private key is held by their developer. This
certificate identifies the author of the app. The certificate does not need to be signed by a
certificate authority; it is perfectly allowable, and typical, for Android apps to use self-signed
certificates. The purpose of certificates in Android is to distinguish app authors. This allows the
system to grant or deny apps access to signature-level permissions and to grant or deny an
app's request to be given the same Linux identity as another app.

User IDs and file access


At install time, Android gives each package a distinct Linux user ID. The identity remains
constant for the duration of the package's life on that device. On a different device, the same
package may have a different UID; what matters is that each package has a distinct UID on a
given device.

Because security enforcement happens at the process level, the code of any two packages cannot
normally run in the same process, since they need to run as different Linux users. You can use
the sharedUserId attribute in the AndroidManifest.xml's manifest tag of each package
to have them assigned the same user ID. By doing this, for purposes of security the two packages
are then treated as being the same app, with the same user ID and file permissions. Note that in
order to retain security, only two apps signed with the same signature (and requesting the same
sharedUserId) will be given the same user ID.

Any data stored by an app will be assigned that app's user ID, and not normally accessible to
other packages.

Defining and enforcing permissions


To enforce your own permissions, you must first declare them in
your AndroidManifest.xml using one or more <permission> elements.

For example, an app that wants to control who can start one of its activities could 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>

Note: The system does not allow multiple packages to declare a permission with the same
name, unless all the packages are signed with the same certificate. If a package declares a
permission, the system does not permit the user to install other packages with the same
permission name, unless those packages are signed with the same certificate as the first
package. To avoid naming collisions, we recommend using reverse-domain-style naming for
custom permissions, for example com.example.myapp.ENGAGE_HYPERSPACE.

The protectionLevel attribute is required, telling the system how the user is to be informed
of apps requiring the permission, or who is allowed to hold that permission, as described in the
linked documentation.

The android:permissionGroup attribute is optional, and only used to help the system
display permissions to the user. In most cases you should set this to a standard system group
(listed in android.Manifest.permission_group), although you can define a group
yourself. It is preferable to use an existing group, as this simplifies the permission UI shown to
the user.

You need to supply both a label and description for the permission. These are string resources
that the user can see 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 of sentences describing what the permission allows a holder to do. Our convention is a
two-sentence description: the first sentence describes the permission, and the second sentence
warns the user of the type of things that can go wrong if an app 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 app to call
phone numbers without your intervention. Malicious apps may
cause unexpected calls on your phone bill. Note that this does not
allow the app to call emergency numbers.</string>

Create a permission group


As shown in the previous section, you can use the android:permissionGroup attribute to
help the system describe permissions to the user. In most cases you will want to set this to a
standard system group (listed in android.Manifest.permission_group), but you can
also define your own group with <permission-group>.

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. The <permission-
group> element does not specify the permissions that belong to the group, but it gives the group
a name.

You can place a permission in the group by assigning the group name to
the <permission> element's permissionGroup attribute.

The <permission-tree> element declares a namespace for a group of permissions that are
defined in code.

Custom permission recommendations


Apps can define their own custom permissions and request custom permissions from other apps
by defining <uses-permission> elements. However, you should carefully assess whether it
is necessary for your app to do so.

 If you are designing a suite of apps that expose functionality to one another, try to design the apps
so that each permission is defined only once. You must do this if the apps are not all signed with
the same certificate. Even if the apps are all signed with the same certificate, it's a best practice to
define each permission once only.
 If the functionality is only available to apps signed with the same signature as the providing app,
you may be able to avoid defining custom permissions by using signature checks. When one of
your apps makes a request of another of your apps, the second app can verify that both apps are
signed with the same certificate before complying with the request.

Application Deployment
Publish your app
Publishing is the general process that makes your Android applications available to users. When
you publish an Android application you perform two main tasks:

 You prepare the application for release.


 During the preparation step you build a release version of your application, which users can
download and install on their Android-powered devices.
 You release the application to users.
 During the release step you publicize, sell, and distribute the release version of your application
to users.
 This page provides an overview of the process you should follow as you prepare to publish your
app. If you plan to publish on Google Play, you should also read the Google Play launch
checklist.

Preparing your app for release


Preparing your application for release is a multi-step process that involves the following tasks:

 Configuring your application for release.

At a minimum you need to remove Log calls and remove the android:debuggable attribute
from your manifest file. You should also provide values for
the android:versionCode and android:versionName attributes, which are located in
the <manifest> element. You may also have to configure several other settings to meet Google
Play requirements or accommodate whatever method you're using to release your application.
If you are using Gradle build files, you can use the release build type to set your build settings for
the published version of your app.
 Building and signing a release version of your application.

You can use the Gradle build files with the release build type to build and sign a release version
of your application.
 Testing the release version of your application.

Before you distribute your application, you should thoroughly test the release version on at least
one target handset device and one target tablet device.
 Updating application resources for release.
You need to be sure that all application resources such as multimedia files and graphics are
updated and included with your application or staged on the proper production servers.
 Preparing remote servers and services that your application depends on.

If your application depends on external servers or services, you need to be sure they are secure
and production ready.
You may have to perform several other tasks as part of the preparation process. For example, you
will need to get a private key for signing your application. You will also need to create an icon
for your application, and you may want to prepare an End User License Agreement (EULA) to
protect your person, organization, and intellectual property.
When you are finished preparing your application for release you will have a signed .apk file that
you can distribute to users.

Releasing your app to users


You can release your Android applications several ways. Usually, you release applications
through an application marketplace such as Google Play, but you can also release applications on
your own website or by sending an application directly to a user.

Releasing through an app marketplace


If you want to distribute your apps to the broadest possible audience, releasing through an app
marketplace such as Google Play is ideal.
Google Play is the premier marketplace for Android apps and is particularly useful if you want to
distribute your applications to a large global audience. However, you can distribute your apps
through any app marketplace you want or you can use multiple marketplaces.

Releasing your apps on Google Play


Google Play is a robust publishing platform that helps you publicize, sell, and distribute your
Android applications to users around the world. When you release your applications through
Google Play you have access to a suite of developer tools that let you analyze your sales, identify
market trends, and control who your applications are being distributed to. You also have access to
several revenue-enhancing features such as in-app billing and application licensing. The rich
array of tools and features, coupled with numerous end-user community features, makes Google
Play the premier marketplace for selling and buying Android applications.

Releasing your application on Google Play is a simple process that involves three basic steps:

 Preparing promotional materials.

To fully leverage the marketing and publicity capabilities of Google Play, you need to create
promotional materials for your application, such as screenshots, videos, graphics, and
promotional text.

 Configuring options and uploading assets.

Google Play lets you target your application to a worldwide pool of users and devices. By
configuring various Google Play settings, you can choose the countries you want to reach, the
listing languages you want to use, and the price you want to charge in each country. You can also
configure listing details such as the application type, category, and content rating. When you are
done configuring options you can upload your promotional materials and your application as a
draft (unpublished) application.
 Publishing the release version of your application.

If you are satisfied that your publishing settings are correctly configured and your uploaded
application is ready to be released to the public, you can simply click Publish in the Play Console
and within minutes your application will be live .andavailable for download around the world.

Releasing through a website


If you do not want to release your app on a marketplace like Google Play, you can make the app
available for download on your own website or server, including on a private or enterprise server. To
do this, you must first prepare your application for release in the normal way. Then all you need to do
is host the release-ready APK file on your website and provide a download link to users.

When users browse to the download link from their Android-powered devices, the file is downloaded
and Android system automatically starts installing it on the device. However, the installation process
will start automatically only if the user has configured their Settings to allow the installation of apps
from unknown sources.

Although it is relatively easy to release your application on your own website, it can be inefficient.
For example, if you want to monetize your application you will have to process and track all financial
transactions yourself and you will not be able to use Google Play's In-app Billing service to sell in-
app products. In addition, you will not be able to use the Licensing service to help prevent
unauthorized installation and use of your application.

Publishing Android Application


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.

Android development life cycle

Once you developed and fully tested your Android Application, you can start selling or
distributing free using Google Play (A famous Android marketplace). You can also release your
applications by sending them directly to users or by letting users download them from your own
website.
You can check a detailed publishing process at Android official website, but this tutorial will
take you through simple steps to launch your application on Google Play. Here is a simplified
check list which will help you in launching your Android application −
Ste Activity
p

1 Regression Testing Before you publish your application, you need to make sure that its
meeting the basic quality expectations for all Android apps, on all of the devices that you are
targeting. So perform all the required testing on different devices including phone and tablets.

2 Application Rating When you will publish your application at Google Play, you will have to
specify a content rating for your app, which informs Google Play users of its maturity level.
Currently available ratings are (a) Everyone (b) Low maturity (c) Medium maturity (d) High
maturity.

3 Targeted Regions Google Play lets you control what countries and territories where your
application will be sold. Accordingly you must take care of setting up time zone, localization or
any other specific requirement as per the targeted region.

4 Application Size Currently, the maximum size for an APK published on Google Play is 50 MB.
If your app exceeds that size, or if you want to offer a secondary download, you can use APK
Expansion Files, which Google Play will host for free on its server infrastructure and
automatically handle the download to devices.

5 SDK and Screen Compatibility It is important to make sure that your app is designed to run
properly on the Android platform versions and device screen sizes that you want to target.

6 Application Pricing Deciding whether you app will be free or paid is important because, on
Google Play, free app's must remain free. If you want to sell your application then you will have
to specify its price in different currencies.

7 Promotional Content It is a good marketing practice to supply a variety of high-quality graphic


assets to showcase your app or brand. After you publish, these appear on your product details
page, in store listings and search results, and elsewhere.

8 Build and Upload release-ready APK The release-ready APK is what you you will upload to
the Developer Console and distribute to users. You can check complete detail on how to create
a release-ready version of your app: Preparing for Release.

9 Finalize Application Detail Google Play gives you a variety of ways to promote your app and
engage with users on your product details page, from colourful graphics, screen shots, and
videos to localized descriptions, release details, and links to your other apps. So you can
decorate your application page and provide as much as clear crisp detail you can provide.

Export Android Application Process

Apk development process

Before exporting the apps, you must some of tools


 Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it has useful
for memory optimization and reduce the boot-up speed time
 AAPT(Android assistance packaging tool):it has useful to convert .Dex file to.Apk
 APK(Android packaging kit): The final stage of deployment process is called as .apk.
You will need to export your application as an APK (Android Package) file before you upload it
Google Play marketplace.
To export an application, just open that application project in Android studio and select Build →
Generate Signed APK from your Android studio and follow the simple steps to export your
application −

Next select, Generate Signed APK option as shown in the above screen shot and then click it
so that you get following screen where you will choose Create new keystore to store your
application.
Enter your key store path,key store password,key alias and key password to protect your
application and click on Next button once again. It will display following screen to let you
create an application −

Once you filled up all the information,like app destination,build type and flavours
click finish button While creating an application it will show as below

Finally, it will generate your Android Application as APK formate File which will be uploaded
at Google Play marketplace.

Google Play Registration


The most important step is to register with Google Play using Google Play Marketplace. You
can use your existing google ID if you have any otherwise you can create a new Google ID and
then register with the marketplace. You will have following screen to accept terms and
condition.
You can use Continue to payment button to proceed to make a payment of $25 as a
registration fee and finally to complete your account detail.
Once you are a registered user at Google Play, you can upload release-ready APK for your
application and finally you will complete application detail using application detail page as
mentioned in step 9 of the above mentioned checklist.

Signing Your App Manually


You do not need Android Studio to sign your app. You can sign your app from the command
line using standard tools from the Android SDK and the JDK. To sign an app in release mode
from the command line −

 Generate a private key using keytool


$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000

 Compile your app in release mode to obtain an unsigned APK

Sign your app with your private key using jarsigner

$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1


-keystore my-release-key.keystore my_application.apk alias_name

 Verify that your APK is signed. For example −


$ jarsigner -verify -verbose -certs my_application.apk
 Align the final APK package using zipalign.
$ zipalign -v 4 your_project_name-unaligned.apk
your_project_name.apk

You might also like