Mobile Application Development Chapter 6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 138

Chapter 6

Package is
android.provider.Telephony.Sms
Contains all text-based SMS messages.
Nested Class
Telephony.Sms.Draft
Contains all draft text-based SMS messages in the SMS app.
Telephony.Sms.Inbox
Contains all text-based SMS messages in the SMS app inbox.
Telephony.Sms.Intents
Contains constants for SMS related Intents that are broadcast.
Telephony.Sms.Outbox
Contains all pending outgoing text-based SMS messages.
Telephony.Sms.Sent
Contains all sent text-based SMS messages in the SMS app.
Telephony.Sms.Conversations
Contains a view of SMS conversations (also referred to as threads).
• send SMS from our android application in two
ways either by using SMSManager API
or Intents .
• 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.
1.Android Send SMS using
SMSManager API
• SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(MobileNumber,null,Message,n
ull,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.S
END_SMS"/>

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"
MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.provider.Telephony;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class 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,txtMessage.getText().toSt
ring(),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
• <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.sendsmsexample">
<uses-permission android:name="android.permission.SEND_SMS"/>
<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" />
</intent-filter>
</activity>
</application>
</manifest>
2.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
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"/>
btnSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("smsto:"));
i.setType("vnd.android-dir/mms-sms");
i.putExtra("address", new String(txtMobile.getText().toStrin
g()));
i.putExtra("sms_body",txtMessage.getText().toString());
startActivity(Intent.createChooser(i, "Send sms
via:"));
}
catch(Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to
Send, Please try again", Toast.LENGTH_SHORT).show();
}
Receive SMS
• Receive SMS Permissions
– We only need receive
permission android.permission.RECEIVE_SMS. In
case you also want to read SMS messages from the
Inbox then you need android.permission.READ_SMS.
Intent Filter to receive SMS
• We also need to tell Android that we want to handle
incoming SMS messages. In order to do this, we will add
a <receiver> to register a broadcast receiver to the manifest
XML. We will also add an <intent-filter> to let Android know
that we want to launch a specific class when an SMS comes
in.

<receiver
android:name="com.javarticles.android.SMSReceiver">
<intent-filter>
<action
android:name="android.provider.Telephony.SMS_RECEIVED"
/>
</intent-filter>
Broadcast Receiver

• SMSReceiver is a BroadcastReceiver. When


SMS is received, onReceive will be called. Here
we will look into the interested numbers
based on a setting. If the message has
originated from one of those numbers, we will
launch a new Activity, and pass the phone
number and the SMS message to the activity.
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;

public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

String phoneNumbers = PreferenceManager.getDefaultSharedPreferences(


context).getString("phone_entries", "");
StringTokenizer tokenizer = new StringTokenizer(phoneNumbers, ",");
Set<String> phoneEnrties = new HashSet<String>();
while (tokenizer.hasMoreTokens()) {
phoneEnrties.add(tokenizer.nextToken().trim());
}
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i]= SmsMessage.createFromPdu((byte[]) pdus[i]);
String address = messages[i].getOriginatingAddress();
if (phoneEnrties.contains(address)) {
Intent newintent = new Intent(context, MainActivity.class);
newintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newintent.putExtra("address", address);
newintent.putExtra("message",
messages[i].getDisplayMessageBody());
context.startActivity(newintent);
}
}
}
}
Main Activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {


public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String address = extras.getString("address");
String message = extras.getString("message");
TextView addressField = (TextView) findViewById(R.id.address);
TextView messageField = (TextView) findViewById(R.id.message);
addressField.setText(address);
messageField.setText(message);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.settings:
startActivity(new Intent(this, SettingsActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
Activity_main.xml
<LinearLayout 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"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.javarticles.android.DatePickerExample" >

<TextView
android:id="@+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="18dp"
android:text="@string/welcome"
android:textColor="@color/welcome_text_color"
android:textSize="20sp" />

<TextView
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javarticles.android"
android:versionCode="1"
android:versionName="1.0" >
AndroidManifest.xml:
<uses-sdk
android:maxSdkVersion="22"
android:minSdkVersion="14"
android:targetSdkVersion="22" />

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher_sandbox"
android:label="@string/app_name" >
<activity android:name="com.javarticles.android.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name="com.javarticles.android.SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

</application>
</manifest>
Email
• To compose an email, use one of the below actions based on whether
you'll include attachments, and include email details such as the
recipient and subject using the extra keys listed below.
• ActionACTION_SENDTO (for no attachment) or
• ACTION_SEND (for one attachment) or
• ACTION_SEND_MULTIPLE (for multiple attachments)
• MIME Type
– "text/plain"“
– */*“
• Extras
– Intent.EXTRA_EMAIL A string array of all "To" recipient email addresses.
– Intent.EXTRA_CC A string array of all "CC" recipient email addresses.
– Intent.EXTRA_BCC A string array of all "BCC" recipient email addresses
– Intent.EXTRA_SUBJECT A string with the email subject.
– Intent.EXTRA_TEXT A string with the body of the email.
– Intent.EXTRA_STREAM A Uri pointing to the attachment. If using
the ACTION_SEND_MULTIPLE action, this should instead be
an ArrayList containing multiple Uri objects.
• public void composeEmail(String[] addresses, String
subject, Uri attachment) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_STREAM,
attachment);
if (intent.resolveActivity(getPackageManager()) !=
null) {
startActivity(intent);
}
}
• If you want to ensure that your intent is handled only by an email
app (and not other text messaging or social apps), then use
the ACTION_SENDTO action and include the "mailto:" data scheme.

• For example:
public void composeEmail(String[] addresses, String subject)
{
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should
handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
}
• <activity ...>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<data android:type="*/*" />
<category
android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SENDTO"
/>
<data android:scheme="mailto" />
<category
android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="22dp"
android:layout_marginTop="18dp"/>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignLeft="@+id/editText1"
android:layout_marginTop="20dp"
/>
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2" />
<TextView
android:id="@+id/textView1"
android:textColor="#0F9D58"
android:text="Send To:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"/> <TextView
android:id="@+id/textView2"
android:textColor="#0F9D58"
android:text="Email Subject:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"/>
<TextView
android:id="@+id/textView3"
android:textColor="#0F9D58"
android:text="Email Body:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText3"
android:layout_alignBottom="@+id/editText3"/>
<Button
android:id="@+id/button"
android:text="Send email!!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_below="@+id/editText3"
android:layout_marginLeft="76dp"
android:layout_marginTop="20dp"/> </RelativeLayout>
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnClickListener;
import android.net.Uri;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

// define objects for edit text and button


Button button;
EditText sendto, subject, body;

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

// Getting instance of edittext and button


sendto = findViewById(R.id.editText1);
subject = findViewById(R.id.editText2);
body = findViewById(R.id.editText3);
button = findViewById(R.id.button);
// attach setOnClickListener to button
// with Intent object define in it
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view)
{
String emailsend = sendto.getText().toString();
String emailsubject = subject.getText().toString();
String emailbody = body.getText().toString();

// define Intent object


// with action attribute as ACTION_SEND
Intent intent = new Intent(Intent.ACTION_SEND);

// add three fiels to intent using putExtra function


intent.putExtra(Intent.EXTRA_EMAIL,
new String[] { emailsend });
intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject);
intent.putExtra(Intent.EXTRA_TEXT, emailbody);

// set type of intent


intent.setType("message/rfc822");

// startActivity with intent with chooser


// as Email client using createChooser function
startActivity(
Intent
.createChooser(intent,
"Choose an Email client :"));
}
});
}
}
Phone call
phone call from our android applications by invoking built-in phone calls app
using Intents action (ACTION_CALL).

Generally, the Intent object in android with proper action (ACTION_CALL) and data will
help us to launch a built-in phone calls app to make a phone calls in our application.

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 know more about an Intent object in android check this Android
Intents with Examples.

To make a phone call using Intent object in android application, we need to write the
code like as shown below.

Intent callIntent = new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:" + txtPhone.getText().toString()));
startActivity(callIntent);
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">
</EditText>
<Button
android:id="@+id/btnCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Call" />
</LinearLayout>
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
MainActivity.java
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {


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

//Getting the edittext and button instance


edittext1=(EditText)findViewById(R.id.editText1);
button1=(Button)findViewById(R.id.button1);

//Performing action on button click


button1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
String number=edittext1.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+number));
startActivity(callIntent);
}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
Android Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
package="com.example.phonecall"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />

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


<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.phonecall.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>
Location Based Services

• Location Based Services are provided by


Android through its location framework. The
framework provides a location API which
consists of certain classes and interface. These
classes and interface are the key components
which allow us to develop Location Based
Application in Android.
Classes and Interfaces of Location
Based Services:
• LocationManager – This class helps to get
access to the location service of the system.
• LocationListener – This interface acts as the
listener which receives notification from the
location manager when the location changes
or the location provider is disabled or enabled.
• Location – This is the class which represents
the geographic location returned at a
particular time.
Location class
• A data class representing a geographic location.
• A location can consist of a latitude, longitude,
timestamp, and other information such as
bearing, altitude and velocity.
• All locations generated by
the LocationManager are guaranteed to have a
valid latitude, longitude, and timestamp (both
UTC time and elapsed real-time since boot), all
other parameters are optional.
methods
static void distanceBetween(double startLatitude, double startLongitude, double
endLatitude, double endLongitude, float[] results)Computes the
approximate distance in meters between two locations, and optionally
the initial and final bearings of the shortest path between them.
float distanceTo(Location dest)Returns the approximate distance in meters
between this location and the given location.
void dump(Printer pw, String prefix)
float getAccuracy()Get the estimated horizontal accuracy of this location,
radial, in meters.
double getAltitude()Get the altitude if available, in meters above the WGS 84
reference ellipsoid.
double getLatitude()Get the latitude, in degrees.
double getLongitude()Get the longitude, in degrees.
float getSpeed()Get the speed if it is available, in meters/second over ground.
To get API Key
• Visit the Google Cloud Platform Console.
• Click the project drop-down and select or create the project
for which you want to add an API key.
• Click the menu button and select APIs & Services >
Credentials.
• On the Credentials page, click Create credentials > API key.
The API key created dialog displays your newly created API
key.
• Click Close.
The new API key is listed on the Credentials page under API
keys.
(Remember to restrict the API key before using it in
production.)
Add the API key to your app
Follow the steps below to include the API key in your application's
manifest, contained in the file AndroidManifest.xml.

1.In AndroidManifest.xml, add the following element as a child of


the <application> element, by inserting it just before the closing
</application> tag:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>

2. In the value attribute, replace YOUR_API_KEY with your API


key (the encrypted string). This element sets the
key com.google.android.geo.API_KEY to the value of your API key.

Save AndroidManifest.xml and re-build your application.


Google Map Types

• A MapType is an interface that defines the


display and usage of map tiles and the
translation of coordinate systems from screen
coordinates to world coordinates (on the
map). Each MapType must contain a few
methods to handle retrieval and release of
tiles, and properties that define its visual
behavior.
Basic Google Map Types
There are four types of maps available within the Maps
JavaScript API. In addition to the familiar "painted" road
map tiles, the Maps JavaScript API also supports other
maps types.
The following map types are available in the Maps
JavaScript API:
• roadmap
– displays the default road map view. This is the default map
type.
• satellite
– displays Google Earth satellite images.
• hybrid
– displays a mixture of normal and satellite views.
• Terrain
– displays a physical map based on terrain information.
Syntax of different types of map

• googleMap.setMapType(GoogleMap.MAP_TY
PE_NORMAL);
• googleMap.setMapType(GoogleMap.MAP_TY
PE_HYBRID);
• googleMap.setMapType(GoogleMap.MAP_TY
PE_SATELLITE);
• googleMap.setMapType(GoogleMap.MAP_TY
PE_TERRAIN);
Methods of Google map
Methods Description
addCircle(CircleOptions options) This method add circle to map.
addPolygon(PolygonOptions options) This method add polygon to map.
addTileOverlay(TileOverlayOptions This method add tile overlay to the map.
options)
animateCamera(CameraUpdate This method moves the map according to
update) 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.SnapshotReadyC This method takes a snapshot of the map.
allback callback)
stopAnimation() This method stops the camera animation if
there is any progress.
Example of Google Map
Copy the URL from
google_map_api.xml file to generate
Google map key.
Paste the copied URL at the browser. It
will open the following page.
Click on Create API key to generate API
key.
After clicking on Create API key, it will
generate our API key displaying the
following screen.
Copy this generated API key in
our google_map_api.xml file
activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/r
es/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.SupportMap
Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.mapexample.MapsActivity" />
MapsActivity.java
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);

}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Add a marker in Sydney and move the camera


LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("
Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.mapexample">
<!--
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:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

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

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:2
6.1.0'
implementation 'com.google.android.gms:play-services-
maps:11.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:
runner:1.0.1'
androidTestImplementation 'com.android.support.test.
espresso:espresso-core:3.0.1'
}
Android Google Map Displaying
Current Location
• Callback methods in Google Map
• 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.
• 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.
• 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.
• The setMyLocationEnabled() method of GoogleMap is used to enable
activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/r
es/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.SupportMap
Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.mapexample.MapsActivity" />
build.gradel

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.google.android.gms:play-services-maps:11.8.
0'
compile 'com.google.android.gms:play-services-location:11.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.
1'
androidTestImplementation 'com.android.support.test.espresso:es
presso-core:3.0.1'

}
MapsActivity.java

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

import com.google.android.gms.common.api.GoogleApiClient;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationServices;

import android.location.Location;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
public class MapsActivity extends FragmentActivity implements OnMapRead
yCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{

private GoogleMap mMap;


Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is rea
dy to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSuppo
rtFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}

}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {

mLocationRequest = new LocationRequest();


mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {

@Override
public void onLocationChanged(Location location) {

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mCurrLocationMarker = mMap.addMarker(markerOptions);

//move map camera


mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
<?xml version="1.0" encoding="utf-8"?>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.mapexample">
<!--
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:roundIcon="@mipmap/ic_launcher_round"
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="@string/google_maps_key" />

<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>
Zoom Controls
• The Zoom Controls class displays a simple set of
controls used for zooming and provides callbacks
to register for events.
• Xml code
<ZoomControls android:id="@+id/zoomControls1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
public class MainActivity extends Activity
{
ZoomControls zoom;
Button hide,show;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
zoom = (ZoomControls) findViewById(R.id.zoomControls1);
hide = (Button) findViewById(R.id.button1);
show = (Button) findViewById(R.id.button2);
show.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) {
zoom.show();
}};

hide.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) {


zoom.hide();
}};
Show marker on location
Step 1
• An instance of the LocationManager needs to be
created as the first step in this process. This is the
main class through which the application gets
access to the location services in Android. A
reference to this system service can be obtained
by calling getSystemService() method.

LocationManager locationManager =
(LocationManager)getSystemService(Context.LOC
ATION_SERVICE);
Step 2
• identify the location provider you would like to use for retrieving location details.
The location providers actually provide the location data in Android. Android
exposes two main location providers:

1. GPS Location Provider:


This location provider provides location data with the highest accuracy (~2 m – 20m).
Location updates are provided through satellites. However there are some
drawbacks with this provider which are explained as below:

– A. It is significantly slower than the network provider to get the initial connection setup
with the satellites. This initial connection, also called Time to First Fix (TTFF) can be
extremely slow but once the connection is established, location updates are quite fast
– B. GPS provider also drains out the battery very first. So, it is very important to judiciously
use this provider. Special care should be taken to ensure that this is turned off when you
are not using it.
– C. The third draw back comes from the fact that GPS uses radio signal which is obstructed
by solid objects. So, GPS provider will not work if you are inside a building or in a basement.

2. Network Provider:
This provider uses Wi-Fi hotspots and cell tower to approximate a location. The
provider retrieves an approximate location by querying the Google location server
using the IDs of the Wi-Fi hotspots and cell towers. Location accuracy is between 100
– 1000 m. The location accuracy is directly proportional to the number of Wi-Fi
hotspots and cell towers available in the area.
You can check the availability of the providers
using the below piece of code:

isGpsEnabled = mLocManager.isProviderEnab
led(LocationManager.GPS_PROVIDER);
isNetworkEnabled =
mLocManager.isProviderEnabled(LocationMa
nager.NETWORK_PROVIDER);
Step 3
To register a location listener with the location manager.
The registration can be done by calling the
method requestLocationUpdates((String provider, long minTime, float
minDistance, LocationListener listener).
Following are the parameters passed to this method:
– provider:
the name of the provider with which to register. This can be either GPS or
Network provider.
– minTime:
minimum time interval between location updates, in milliseconds.
– minDistance:
minimum distance between location updates, in meters.
– listener:
a LocationListener whose onLocationChanged(Location) method will be called
for each location update.

• The Location Manager calls the onLocationChanged() of the listener when


the mobile has moved a distance greater than the minDistance or the time
since last location update is more than minTime.
Permissions required for Location
Based Services in Android
• <uses-permissionandroid:name=”android.permission.ACCESS_CO
ARSE_LOCATION”/>
<uses-permissionandroid:name=”android.permission.ACCESS_FIN
E_LOCATION”/>
<uses-permissionandroid:name=”android.permission.INTERNET”/
>

For GPS based location, you need only the


“android.permission.ACCESS_FINE_LOCATION”

For Network based location, you need only the


“android.permission.ACCESS_FINE_LOCATION”
If you are using both the providers, you need to request only for
the ACCESS_FINE_LOCATION permission, it includes permission
for both the providers.
Geocode and reverse geocoding
• Android Geocoder class is used for Geocoding as
well as Reverse Geocoding. Geocoding refers to
transforming street address or any address into
latitude and longitude. Reverse Geocoding refers
to transforming latitude and longitude into its
corresponding street address.
• Address class helps in fetching the street address,
locality, sub-locality, city, country, landmark etc.
features of the location.
• We’ve set the attributes setEllipize() and set setMarqueeRepeatLimit() on the
TextView programmatically since setting the same attributes in xml doesn’t scroll
the text on all devices anymore. The above methods make the content of TextView
scroll horizontally IF the content length is greater than the TextView width.
• Passing -1 in setMarqueeRepeatLimit() makes it scroll forever.
• The Google Map is displayed using the
SupportMapFragment. getMapAsync() callback is assigned to the fragment. This
callback gets triggered when the Google Play Services exists.
• The onMapReady() method is the one that displays the Google Map and returns a
non-null instance of the GoogleMap class. We assign it to our instance variable map.
map.getUiSettings().setZoomControlsEnabled(true) is used to set the zoom controls
on the screen.
• map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16)) moves the
map to the location specified in the latLng(Some location in India!). The camera
zooms to the location in the center of the screen where the marker is placed.
• setOnCameraIdleListener would listen for the movements/dragging on the map.
When the movement ends the method onCameraIdle() gets triggered. This is where
we retrieve the latitude and longitude of the center of map(because that is where
the marker resides) and pass it into the method getAddressFromLocation() which
will eventually do the reverse geocoding.
• The method getFromLocation(double latitude, double longitude, int
maxResults) returns a List of Addresses for the current location.
• Within the Address object, the method getAddressLine(int index) returns a line of
the address numbered by the given index or null if no address exists.
• We append that address to a StringBuilder which is eventually displayed in the
TextView.
• getMaxAddressLineIndex() returns the largest index currently in use to specify an address line.
• There are several other important details of an address that can retrieved too. Some of them are
listed below:
– getThoroughfare() : This is the street, which contains the delivery point. If it doesn’t exist null would be
returned.
– getSubThoroughfare() : When a thoroughfare name exists more than once within a town,
subThoroughfare name is used for additional information.
– getLocality() and getSublocality() : Returns the locality of the address, for example “Mountain View” and
sub locality respectively if available or null.
– getFeatureName() : Returns the nearest landmark name if available or null.
– getCountryName() getCountryCode() : Returns the country name and country code respectively.
• Clicking the CardView would launch the PlaceAutoComplete service from the Google Places API.
• We use the PlaceAutocomplete.IntentBuilder to create Intent and pass the Mode as full screen.
• The selected place is returned in the onActivityResult() which is eventually displayed in the
TextView. The latitude and longitude of the Place are returned as place.getLatLng() which is
eventually zoomed into the center of the screen.
Location data
• The location data available to an Android device includes
the current location of the device — pinpointed using a
combination of technologies — the direction and method of
movement, and whether the device has moved across a
predefined geographical boundary, or geofence. Depending
upon the needs of your application, you can choose
between several ways of working with location data:
• The My Location layer provides a simple way to display a
device's location on the map. It does not provide data.
• The Google Play services Location API is recommended for
all programmatic requests for location data.
• The LocationSource interface allows you to provide a
custom location provider.
LocationSource

• public interface LocationSource


• Defines an interface for providing location data, typically to
a GoogleMap object.
• A GoogleMap object has a built-in location provider for its
my-location layer, but it can be replaced with another one that
implements this interface.
• A GoogleMap object activates its location provider
using activate(OnLocationChangedListener). While active
(between activate(OnLocationChangedListener) and deactivate()),
a location provider should push periodic location updates to the
listener registered in activate(OnLocationChangedListener). It is
the provider's responsibility to use location services wisely
according to the map's lifecycle state. For example, it should only
using battery-intensive services (like GPS) occasionally, or only
while an activity is in the foreground.
• Nested Class Summary

interface LocationSource.OnLocationCh Handles a


angedListener location
update.

• Public Method Summary


abstract void activate(LocationSource.OnLo
cationChangedListener listene
r)Activates this provider.
abstract void deactivate()Deactivates this
provider.
• Public Methods
– public abstract
void activate (LocationSource.OnLocationChangedListener liste
ner)
listener that's called when a new location is available
Throws IllegalStateException,IllegalArgumentException
• public abstract void deactivate ()
– Deactivates this provider. The
previously-registered callback is not notified of
any further updates. Throws IllegalStateException
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.
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
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.
Requesting permissions

• To request a permission an app must include


a <uses-permission> tag in its AndroidManifest.xml file.
• <manifest …> <uses-permission
android:name="com.example.myamazingapp.SOME_PERMISSION
"> … </manifest>
• This example requests the permission SOME_PERMISSION in
order to access some capability provided by myamazingapp.
• Android has many built-in permissions that an app can request.
For example, an app can request access to the internet as follows:
• <manifest …> <uses-permission
android:name="android.permission.INTERNET"> … </manifest>
• If the requested permission is a dangerous permission the user
will have to agree to grant the app that permission.
Enforcing permissions

• To use a permission to control access to a component an app can


add an android:permission attribute to the component’s
declaration in the app’s AndroidManifest.xml file.
• <manifest …> <application …> <activity
android:name="com.example.myamazingapp.SomeActivity"
android:permission="com.example.myamazingapp.SOME_PERMIS
SION"> </activity> </application> </manifest>
• In the above example, for an app to start SomeActivity (a
component of myamazingapp) it must have requested, and been
granted, the permission SOME_PERMISSION.
• The android:permission attribute can also be set for
the <application> element in the app’s AndroidManifest.xml file.
This becomes the overall default permission for all the app’s
components that do not have their own attribute:permission set.
Permissions and the Principle of Least
Privilege
• The tag <uses-permission> is used to request a
permission, and the
attribute android:permission is used to enforce a
permission.
• If a component enforces a particular permission,
then your app must request that permission if it
wants to access that component.
• Following the Principle of Least Privilege, only
request those permissions that your app really
needs to perform its function.
Generate Signed Apk for Android App
• Step 1: Go to build and click on Generate
Signed Apk…
Step 2: Android Studio will now open a
dialog box. Click on Next.
Step 3: Now you will need to create
Keystore path. Click on Create new…
Step 4: Now locate key store path in your
system where you want to save jks file of
your project. Click on … to locate the
path.
Step 5: After locating the path from
your system. Give any name to the jks
file that will be created and click ok.
Step 6: Fill the other details and click
ok. For example you can refer to the
image below:
Step 7: Click next.
Step 8: Now edit the destination folder of signed apk file, choose
build type and select signature versions. Finally click Finish:

Important Note: Regarding signature versions, you can


consider V2 because it offers faster app install times and more
protection against unauthorized alterations to APK files. If you
face any problem then you can consider the traditional V1
signing scheme, which uses JAR signing.
Step 9: Now you can use this signed
apk for publishing app on Playstore via
your developer console.

• Important Note 1: After you generate signed apk,


it is very important to keep jks file safe and
secure. If you lost it then you won’t be able to
send future updates to your App.
• Important Note 2: Make sure to keep Keystore
and key password saved somewhere with you. If
you lost or forget it then also you won’t be able to
send new updates for your App.
How To Publish Android App On
PlayStore
• Step 1: First generate signed apk of your
Android App to publish it on Play Store.
• Step 2: Now you will need to sign up for
Google Play Console to publish and manage
your Android App.
• Important Note: You can signup with this
link https://play.google.com/apps/publish/
• Step 3: Login with your Gmail account that
you want to use for publishing App on Play
Store.
• Step 4: Now there are 4 steps to complete the
registration for Google play store console. You
have already completed two.
• Step 5: After reading the Google play store
developer distribution agreement agree to
their terms by clicking on check box
• Step 6: Now you will need to pay one time
‘Developer Registration Fee’ of $25 to Google.
Please fill your credit card details to make the
payment.
• Important Note: You can upload unlimited number of
Android App on Play store from single account with a limit of
uploading 15 apk/day.
• Step 7: Complete your account details for Google
developer account. For example see the below
image:

• Step 8: Now click on Create Application


Step 9: Enter the name of your App.
Step 10: Now fill store listing details of
your App which include Title, Short
description, and Full description.
Step 11: After this you need to put
some App screenshots here. The
minimum required are 2 screenshots
and maximum limit is 8.
• Step 12: After screenshot now you need to
put a high Resolution icon or logo with a size
of 512 * 512 pixel. This will be displayed on
Play Store.
• After that another mandatory thing is you
need to put a feature graphic of 1024 * 500
pixel dimension. See below image for more
detail.
• Step 13: Now scroll down and fill other details which include
application type, category, website, email and phone no.
• After this check privacy policy because now we are not
submitting and then click on save draft. If your App require
user permission then it is mandatory to put privacy url.
• Click on Save Draft to save your work so far.
Step 14: After saving data on draft now
go to app release and click on manage
production.

Step 15: Now you will see create


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

• Step 17: Once the upload is successful then


scroll down and click on review to check.
Step 18: Now go to Content Rating and
click on continue.
Step 19: Fill details which include email
address and select your categories
• Step 20: Now select Violence, Sexuality,
Language, Controlled Substance and
Miscellaneous based on your App. First click
on save questionnaire for save and then click
on calculate rating.
Step 21: Now click on apply rating.
• Step 22: Click on pricing and distribution and
select free/paid based on how you want user
to access your App.

• Step 23: Now scroll down and see mandatory
things with * you need to select After this click
on save draft .

• Step 24: Now Click on ready on publish along


with save draft and click on Manage release.
• Step 25: Click on Manage Production.
• Step 26: After Manage production click on
edit release.

• Step 27: Now click on review.


• Step 28: After review click on Start Rollout to
production. Now you need to confirm. After
confirm you will need to wait for one or six
hour for approval.
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.
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
– Building and signing a release version of your
application
– Testing the release version of your application
– Updating application resources for release.
– Preparing remote servers and services that your
application depends on.
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
– Releasing your apps on Google Play
• Preparing promotional materials
• Configuring options and uploading assets
• Publishing the release version of your application.
Google Play Developer Console
• The Google Play Developer Console is your home
for publishing operations and tools.
• Upload apps, build your product pages, configure
prices and distribution, and publish. You can
manage all phases of publishing on Google Play
through the Developer Console, from any web
browser.
• Once you've registered and received verification
by email, you can sign in to your Google Play
Developer Console.
• All Applications
– Start in All Applications, which gives you a quick
overview of your apps, lets you jump to stats,
reviews, and product details, or upload a new app.
• Your Account Details
– Specify basic developer profile information about
yourself or your company on the accounts detail
page. This identifies you to Google Play and your
customers. You can go back at any time to edit the
information and change your settings.
• Your developer profile contains:
– Developer name — displayed on your store listing
page and elsewhere on Google Play.
– Contact information — used by Google only, it isn't
seen by your customers.
– Web site URL — displayed on your store listing page.
– On the account details page you can also add
restricted access for marketers and other teams,
register for a merchant account, or set up test
accounts for Google Play licensing.
• Linking Your Merchant Account
– If you want to sell apps or in-app products, link
your Google Wallet Merchant Account to your
developer profile. Google Play uses the linked
merchant account for financial and tax
identification, as well as for monthly payouts from
sales.
• Multiple User Accounts
– Set up user accounts for other team members to
access different parts of your Developer Console.
• Store Listing Details
– Use the Developer Console to set up a Store Listing
page. This is the home for your app in Google Play. It's
the page users see on their mobile phones or on the
web to learn about your app and download it.
– Upload custom brand assets, screenshots, and videos
to highlight what's great about your app. Provide a
localized description, add notes about the latest
version, and more. You can update your store listing
at any time.
• Upload and Instantly Publish
– From the Developer Console you can quickly upload and
publish a release-ready Android application package file.
The app is a draft until you publish it, at which time Google
Play makes your store listing page and app available to
users—your app appears in the store listings within hours,
not weeks.
– Once your app is published, you can update it as often as
you want: Change prices, configuration, and distribution
options at any time, without needing to update your app
binary.
– As you add features or address code issues, you can publish
an updated binary at any time. The new version is available
almost immediately and existing customers are notified
that an update is ready for download. Users can also
accept automatic updates to your app, so that your
updates are delivered and installed as soon as you publish
them. You can unpublish your apps app at any time.
• Alpha and Beta Testing
– It's always valuable to get real-world feedback from users,
especially before launch. Google Play makes it easy to distribute
pre-release versions of your app to alpha and beta test groups
anywhere in the world.
– In the APK section of your Google Play Developer Console you’ll
find the Alpha Testing and Beta Testing tabs. Here you can
upload versions of your apps’ APK files
• Staged Rollouts
– You can also stage the rollout of your apps using the Production
tab in the APK section of your Google Play Developer Console.
Here you can define the percentage of user who’ll be able to
download your app.
• Multiple APK Support
– In most cases, a single app package (APK) is all you need,
and it’s usually the easiest way to manage and maintain
the app. However, if you need to deliver a different APK to
different devices, Google Play provides a way to do that.
– Multiple APK support lets you create multiple app packages
that use the same package name but differ in their OpenGL
texture compression formats, screen-size support, or
Android platform versions supported. You can simply
upload all the APKs under a single product listing and
Google Play selects the best ones to deliver to users, based
on the characteristics of their devices.
• Selling and Pricing Your Products
– You have tools to set prices for your apps and in-app
products. Your app can be free to download or priced,
requiring payment before download.
– If you publish your app as free, it must remain free for
the life of the app. Free apps can be downloaded by
all users in Google Play.
– If you publish it as priced, you can later change it to
free. Priced apps can be purchased and downloaded
only by users who have registered a form of payment
in Google Play.
• In-app Products
– You can sell in-app products and subscriptions
using Google Play In-app Billing as a way to monetize
your apps. In-app products are one-time purchases,
while subscriptions are recurring charges on a
monthly or annual basis.
– In the In-app Products section for a specific published
or draft APK you:
• Create product lists for in-app products and subscriptions.
• Set prices.
• Publish the products with the app or withdraw obsolete
products.
• Distribution Controls
– Manage which countries and territories your apps will
distribute to. For some countries, you can choose which
carriers you want to target. You can also see the list of
devices your app is available for, based on any distribution
rules declared in its manifest file.
• Geographic targeting
– You can use controls in the Google Play Developer Console
to easily manage the geographic distribution of your apps,
without any changes in your application binary. You can
specify which countries and territories you want to
distribute to, and even which carriers (for some countries).
• Capabilities targeting
– Google Play also lets you control distribution according to device
features or capabilities that your app depends on. There are
several types of dependencies that the app can define in its
manifest, such as hardware features, OpenGL texture
compression formats, libraries, Android platform versions, and
others.
• User Reviews and Crash Reports
– The User reviews section gives you access to user reviews for a
specific app. You can filter reviews in a number of ways to locate
issues more easily and support your customers more effectively.
– Google Play makes it easy for users to submit reviews of your
app for the benefit of other users. The reviews give you usability
feedback, support requests, and details of important
functionality issues direct from your customers.
• App Statistics
– You get detailed statistics on the install performance
of your app.
– See installation metrics measured by unique users as
well as by unique devices. View active installs, total
installs, upgrades, daily installs and uninstalls, and
metrics about ratings.
– Zoom into the installation numbers by metric,
including Android platform version, device, country,
language, app version, and carrier. View the
installation data for each dimension on timeline
charts.

You might also like