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

Mad Unit 6

The document outlines various aspects of Android application development, including methods for obtaining location data, SMS services, and the process for acquiring a map API key. It also details the steps for deploying an app to the Google Play Store, the necessary permissions for accessing user data, and provides a code example for displaying a user's car location. Additionally, it explains geocoding and reverse geocoding using the Geocoder class in Android.

Uploaded by

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

Mad Unit 6

The document outlines various aspects of Android application development, including methods for obtaining location data, SMS services, and the process for acquiring a map API key. It also details the steps for deploying an app to the Google Play Store, the necessary permissions for accessing user data, and provides a code example for displaying a user's car location. Additionally, it explains geocoding and reverse geocoding using the Geocoder class in Android.

Uploaded by

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

SRES’s

Shree Ramchandra College of Engineering, Lonikand, Pune

Unit :6
Subject Name: MAD Model Answer Subject Code:22617

Q.N Answer Marking


o. Scheme
A Name any four methods to get location data in android.. 2M
Ans •float distanceTo(Location dest) (Any
•float getAccuracy() four, ½
•float getBearing() M for
•double getAltitude() one
•double getLatitude() method )
•float getSpeed()
•boolean hasAccuracy()
•boolean hasAltitude()
•boolean hasBearing()
•boolean hasBearing()
•boolean hasSpeed()
•void reset()
•void setAccuracy(float accuracy)
•void setAltitude(double altitude)
B Define SMS service in android application development. 2M
Ans SMS Any 4
• In Android, you can use SmsManager API or devices Built-in SMS application to points 2
send SMS's M
• Android SMS is stored in PDU (protocol description unit) format
• SmsManager class takes care of sending the SMS message.
• We just need to get an instance of it and send the SMS message.
• We need to add permission to SEND_SMS in the Android manifest file.

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

C Describe the process of getting the map API key. 4M


Ans Creating API keys Correct
The API key is a unique identifier that authenticates requests associated with your Steps 4
project marks
for usage and billing purposes. You must have at least one API key associated with
your
project.
1. Browse the site on your browser. https://console. Developers.
Google.com/project
2. Login with your google account.
3. Create a new project by clicking on Create Project option.
4. Add your project name and organization name in the fields present on the screen.
5. Now click on APIs and Services.
6. Enable APIs and services.
7. Select Google maps Android API
8. To create an API key for Maps click on Create credentials option and then select
Prof. khandre H.D. Shree Ramchandra College of Engineering Page 1
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

the API key option


D Describe steps for deploying android application on Google Play Store 4M
Ans Step 1: Create a Developer Account Correct
Before you can publish any app on Google Play, you need to create a Developer steps 4
Account. marks
You can easily sign up for one using your existing Google Account. You’ll need to
pay a one-time registration fee of $25 using your international credit or debit card.
It can take up to 48 hours for your registration to be fully processed.

Step 2: Plan to Sell? Link Your Merchant Account


If you want to publish a paid app or plan to sell in-app purchases, you need to
create a
payments center profile, i.e. a merchant account. A merchant account will let you
manage your app sales and monthly payouts, as well as analyze your sales reports
right in your Play Console.
Step 3: Create an App
Now you have create an application by clicking on ‘Create Application’. Here you
have
to select your app’s default language from the drop-down menu and then type in a
title
for your app. The title of your app will show on Google Play after you’ve
published.
Step 4: Prepare Store Listing
Before you can publish your app, you need to prepare its store listing. These are all
the
details that will show up to customers on your app’s listing on Google Play. You
not
necessarily complete it at once , you can always save a draft and revisit it later
when
you’re ready to publish.
The information required for your store listing is divided into several categories
such as
Product Details containing title, short and full description of the app, Your app’s
title and description should be written with a great user experience in mind. Use the
right keywords, but don’t overdo it. Make sure your app doesn’t come across as
spam-y or promotional, or it will risk getting suspended on the Play Store.
Graphic Assets where you can add screenshots, images, videos, promotional
graphics,
and icons that showcase your app’s features and functionality.
Languages & Translations, Categorization where in category can be selected to
which
your app belong to. Contact Details , Privacy Policy for apps that request access to
sensitive user data or permissions, you need to enter a comprehensive privacy
policy that effectively discloses how your app collects, uses, and shares that data.
Step 5: Upload APK to an App Release
Finally upload your app, by uploading APK file. Before you upload APK, you need
to
create an app release. You need to select the type of release you want to upload
your first app version to. You can choose between an internal test, a closed test, an
open test, and a production release. The first three releases allow you to test out

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 2


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

your app among a select group of users before you make it go live for everyone to
access. This is a safer option because you can analyze the test results and optimize
or fix your app accordingly if you need to before rolling it out to all users. Once
you create a production release, your uploaded app version will become accessible
to everyone in the countries you choose to distribute it in and click on ‘Create
release.’
Step 6: Provide an Appropriate Content Rating If you don’t assign a rating to your
app, it will be listed as ‘Unrated’. Apps that are ‘Unrated’ may get removed from
Google Play. To rate your app, you need to fill out a content rating questionnaire
An appropriate content rating will also help you get to the right audience, which
will eventually improve your engagement rates.
Step 7: Set Up Pricing & Distribution Before you can fill out the details required in
this step, you need to determine your app’s monetization strategy. Once you know
how your app is going to make money, you can go ahead and set up your app as
free or paid. You can always change your app from paid to free later, but you
cannot change a free app to paid. For that, you’ll need to create a new app and set
its price. Step 8: Rollout Release to Publish Your App The final step involves
reviewing and rolling out your release after making sure you’ve taken care of
everything else. Before you review and rollout your release, make sure the store
listing, content rating, and pricing and distribution sections of your app each have a
green check mark next to them. Once you’re sure about the correctness of the
details, select your app and navigate to ‘Release management’ – ‘App releases.’
You can always opt for reviews by clicking on ‘Review’ to be taken to the ‘Review
and rollout release’ screen. Here, you can see if there are any issues or warnings
you might have missed out on. Finally, select ‘Confirm rollout.’ This will also
publish your app to all users in your target countries on Google Play.
e Describe permissions required for android application development. 4M
Ans Declaring and Using Permissions The purpose of a permission is to protect the (2 Marks
privacy of an Android user. Android apps must request permission to access for two
sensitive user data (such as contacts and SMS), as well as certain system features permissi
(such as camera and internet). Depending on the feature, the system might grant the on
permission automatically or might prompt the user to approve the request. explanati
Permissions are divided into several protection levels. The protection level affects on )
whether runtime permission requests are required. There are three protection levels
that affect thirdparty 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 permission is signed by the same
certificate as the app that defines the permission.
Dangerous permissions: 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 must explicitly grant the permission to the app.

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 3


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

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
f Develop an android application to show current location of an user's car. 4M
Ans activity_maps.xml (2 M for
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xml
xmlns:map="http://schemas.android.com/apk/res-auto" code, 1
xmlns:tools="http://schemas.android.com/tools" M java
android:id="@+id/map" code, 1
android:name="com.google.android.gms.maps.SupportMapFragment" M for
android:layout_width="match_parent" permissi
android:layout_height="match_parent" ons )
tools:context="example.com.mapexample.MapsActivity" />
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


OnMapReadyCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{

private GoogleMap mMap;


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

@Override

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 4


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

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;

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_POWE
R_ACCURACY)
;
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 5


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

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(BitmapDescriptorFac
tory.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) {
}
}
Add the following user-permission in AndroidManifest.xml file.
<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" />
Note: only the permission line can be written , no entire code is required for
manifest file.

g State and elaborate the syntax of required class and methods for 4M
Geocoding.

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 6


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

Geocoder: (2 M for
A class for handling geocoding and reverse geocoding. explanati
Geocoding is the process of transforming a street address or other description of a on and
location into a (latitude, longitude) coordinate. syntax of
Reverse geocoding is the process of transforming a (latitude, longitude) coordinate class, 2
into a (partial) address. The amount of detail in a reverse geocoded location M for
description may explanati
vary, for example one might contain the full street address of the closest building, on and
while syntax of
another might contain only a city name and postal code. any two
The Geocoder class requires a backend service that is not included in the core methods)
android
framework.
The Geocoder query methods will return an empty list if there no backend service
in the platform. Use the isPresent() method to determine whether a Geocoder
implementation
exists.
Syntax
Geocoder (Context context)
Constructs a Geocoder localized for the default locale.
Geocoder(Context context, Locale locale)
Constructs a Geocoder localized for the given locale.
Methods with Syntax
a. getFromLocation
Syntax
public List<Address> getFromLocation (double latitude, double longitude, int
maxResults)
public void getFromLocation (double latitude, double longitude, int maxResults,
Geocoder.GeocodeListener listener)
This method returns an array of Addresses that attempt to describe the area
immediately
surrounding the given latitude and longitude. The returned addresses should be
localized
for the locale provided to this class's constructor.
b. getFromLocationName
Syntax :
● public List<Address> getFromLocationName (String locationName, int
maxResults, double lowerLeftLatitude, double lowerLeftLongitude, double
upperRightLatitude, double upperRightLongitude)
● public void getFromLocationName (String locationName, int maxResults,
double lowerLeftLatitude, double lowerLeftLongitude, double
upperRightLatitude, double upperRightLongitude, Geocoder.GeocodeListener
listener)
● public void getFromLocationName (String locationName, int maxResults,
Geocoder.GeocodeListener listener)
● public List<Address> getFromLocationName (String locationName, int
maxResults)
Returns an array of Addresses that attempt to describe the named location, which
may be
a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 7


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

Parkway,
Mountain View, CA", an airport code such as "SFO", and so forth. The returned
addresses should be localized for the locale provided to this class's constructor.

c.isPresent
Syntax
public static boolean isPresent ()
Returns true if there is a geocoder implementation present that may return results. If
true,
there is still no guarantee that any individual geocoding attempt will succeed

h Develop an application to display Google map with user's current location. (Note : 6M
Consider the appropriate XML file. All attributes are not required. In java file all
imports are not expected. Different relevant logic/code can be considered.)
Ans activity_main.xml XML
<?xml version="1.0" encoding="utf-8"?> file: 1M
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" Java
xmlns:app="http://schemas.android.com/apk/res-auto" Code:
xmlns:tools="http://schemas.android.com/tools" 5M
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/google_map"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
MainActivity.Java
package com.example.location;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
public class MainActivity extends FragmentActivity implements

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 8


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

OnMapReadyCallback
{
Location currentlocation;

FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null)
{
currentlocation=location;

Toast.makeText(getApplicationContext(),currentlocation.getLatitude()+""+current
location.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment =
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.go
ogle_map);
supportMapFragment.getMapAsync(MainActivity.this);
}
}
});
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
LatLng latLng=new
LatLng(currentlocation.getLatitude(),currentlocation.getLongitude());
MarkerOptions markerOptions=new MarkerOptions().position(latLng)
.title("I am Here");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

Prof. khandre H.D. Shree Ramchandra College of Engineering Page 9


SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,5));
googleMap.addMarker(markerOptions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
}
break;
}
}
}
i Write a program to find the direction from user's current location to MSBTE, 6M
Bandra. (Write only Java and manitest file). (Note : Any other relevant logic to get
the required output can also be considered.)
Ans AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.msbte.google_map_currentlocationroute">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
<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.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


10
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

</manifest>
MainActivity.java
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener , OnMapReadyCallback,
TaskLoadedCallback{
//variables for map and route
private GoogleMap mMap;
private MarkerOptions place1, place2;
Button getDirection;
private Polyline currentPolyline;
private MapFragment mapFragment;

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


11
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

private boolean isFirstTime = true;


//variables for current location
private static final String TAG = "MainActivity";
private TextView tvLocation;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */ @Override protected void
onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //code for getting current location
requestMultiplePermissions(); tvLocation = (TextView) findViewById((R.id.tv));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this) .addOnConnectionFailedListener(this)
.addApi(LocationServices.API) .build(); } //code for drawing route @Override
public void onMapReady(GoogleMap googleMap) { mMap = googleMap;
mMap.clear(); Log.d("mylog", "Added Markers"); mMap.addMarker(place1);
mMap.addMarker(place2); CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(22.7739,71.6673)) .zoom(7) .bearing(0) .tilt(45) .build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex),
5000, null); } private String getUrl(LatLng origin, LatLng dest, String
directionMode) { // Origin of route String str_origin = "origin=" + origin.latitude +
"," + origin.longitude; // Destination of route String str_dest = "destination=" +
dest.latitude + "," + dest.longitude; // Mode String mode = "mode=" +
directionMode; // Building the parameters to the web service String parameters =
str_origin + "&" + str_dest + "&" + mode; // Output format String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" +
parameters + "&key=" + getString(R.string.google_maps_key);
return url;
}
@Override
public void onTaskDone(Object... values) {
if (currentPolyline != null)
currentPolyline.remove();
currentPolyline = mMap.addPolyline((PolylineOptions) values[0]);
}
//runtime permission method
private void requestMultiplePermissions(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION )
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


12
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
openSettingsDialog();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest>
permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
@Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ",
Toast.LENGTH_SHORT).show();
}
})
onSameThread() .check(); } private void openSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Required Permissions"); builder.setMessage("This app require
permission to use awesome feature. Grant them in app settings.");
builder.setPositiveButton("Take Me To SETTINGS", new
DialogInterface.OnClickListener() { @Override public void
onClick(DialogInterface dialog, int which) { dialog.cancel(); Intent intent = new
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri =
Uri.fromParts("package", getPackageName(), null); intent.setData(uri);
startActivityForResult(intent, 101); } }); builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() { @Override public void
onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); }
//methods for getting current location @Override public void onConnected(Bundle
bundle) { if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) { return; } startLocationUpdates();
mLocation =
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){ startLocationUpdates(); } if (mLocation != null) { //
mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}}
@Override
public void onConnectionSuspended(int i) {

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


13
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

Log.i(TAG, "Connection Suspended");


mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
tvLocation.setText(String.valueOf(location.getLatitude() +"
"+String.valueOf(location.getLongitude())));
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
if(isFirstTime){
//code to draw path on map
getDirection = findViewById(R.id.btnGetDirection);
getDirection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


14
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

new FetchURL(MainActivity.this).execute(getUrl(place1.getPosition(),
place2.getPosition(), "driving"), "driving");
}
});
place1 = new MarkerOptions().position(new LatLng(location.getLatitude(),
location.getLongitude())).title("Location 1");
place2 = new MarkerOptions().position(new
LatLng(19.021824,72.8662016)).title("MSBTE");
mapFragment = (MapFragment)
getFragmentManager().findFragmentById(R.id.mapNearBy);
mapFragment.getMapAsync(this);
isFirstTime = false;
} }}
j Explain Geocoding and Reverse Geocoding with suitable example. 6M
Ans Geocoding is the process of transforming a street address or other description of a (Geocodi
location into a (latitude, longitude) coordinate. Reverse geocoding is the process of ng ,
transforming a (latitude, longitude) coordinate into a (partial) address. The amount Reverse
of detail in a reverse geocoded location description may vary, for example one Geocodi
might contain the full street address of the closest building, while another might ng
contain only a city name and postal code. Explanati
The Geocoder class is used for handling geocoding and reverse geocoding. on : 3 M,
Example
activity_maps.xml :3M)
<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="example.com.mapexample.MapsActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText
android:layout_width="248dp"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Search Location" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="searchLocation"
android:text="Search" />

</LinearLayout>

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


15
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

</fragment>
AndroidManifest.xml
<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" />
MapsActivity.java
package example.com.mapexample;

import android.location.Address;
import android.location.Geocoder;
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 android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{

private GoogleMap mMap;


Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


16
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

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 ready to be
used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.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_POWE
R_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


17
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

== 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(BitmapDescriptorFac
tory.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) {

public void searchLocation(View view) {


EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


18
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

if (location != null || !location.equals("")) {


Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);

} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(location));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(getApplicationContext(),address.getLatitude()+"
"+address.getLongitude(),Toast.LENGTH_LONG).show();
}
}

}
k Develop an android application for sending Short Message Service (SMS). 6M
Ans activity_main.xml (XML
<?xml version="1.0" encoding="utf-8"?> file 3
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" marks
android:orientation="vertical" android:layout_width="match_parent" Java file
android:layout_height="match_parent"> 3 Marks)
<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" />

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


19
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Send SMS" />
</LinearLayout>
MainActivity.java
package in.org.msbte.sendsmsexample;
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().to
String(),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();
}
}
});
}
}

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


20
SRES’s
Shree Ramchandra College of Engineering, Lonikand, Pune

Prof. khandre H.D. Shree Ramchandra College of Engineering Page


21

You might also like