How to Implement draggable map like uber android, Update with change location - android

How to implement draggable map like uber? I am using Google maps v2. Actually i got the solution referring this post and sharing my complete solution here

Updated with latest code also included change location with autocomplete
Complete project can be found here
Logic is Simple we need a framelayout and add a map and marker layout inside that framelayout then make maker layout gravity to center and get latitude and longitude of the centre point of the map on camera change
refer this answer
here is my code
create activity_maps.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:orientation="vertical">
<TextView android:gravity="center_vertical"
android:id="#+id/Locality"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_btn_current_location"
android:drawablePadding="#dimen/list_row_padding"
android:ellipsize="end"
android:padding="10dp"
android:singleLine="true"
android:text="Click to change location"
android:textSize="#dimen/font_22" />
<EditText
android:id="#+id/Address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:enabled="false"
android:hint="Address"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/container_toolbar">
<fragment
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sample.sishin.maplocation.MapsActivity" />
<LinearLayout
android:id="#+id/locationMarker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="30dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/locationMarkertext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/rounded_corner_map"
android:gravity="center"
android:minWidth="250dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=" Set your Location "
android:textColor="#android:color/white" />
<ImageView
android:id="#+id/imageMarker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/add_marker" />
</LinearLayout>
</FrameLayout>
create TextView backgound xml here rounded_corner_map.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#000000" />
<stroke
android:width="2dp"
android:color="#FFFFFF" />
<padding
android:bottom="8dp"
android:left="1dp"
android:right="1dp"
android:top="8dp" />
<corners
android:bottomLeftRadius="15dp"
android:bottomRightRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
and here is my activity class MainActivity.java
package com.sample.sishin.maplocation;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.os.ResultReceiver;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static String TAG = "MAP LOCATION";
Context mContext;
TextView mLocationMarkerText;
private LatLng mCenterLatLong;
/**
* Receiver registered with this activity to get the response from FetchAddressIntentService.
*/
private AddressResultReceiver mResultReceiver;
/**
* The formatted location address.
*/
protected String mAddressOutput;
protected String mAreaOutput;
protected String mCityOutput;
protected String mStateOutput;
EditText mLocationAddress;
TextView mLocationText;
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mContext = this;
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mLocationMarkerText = (TextView) findViewById(R.id.locationMarkertext);
mLocationAddress = (EditText) findViewById(R.id.Address);
mLocationText = (TextView) findViewById(R.id.Locality);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(getResources().getString(R.string.app_name));
mLocationText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openAutocompleteActivity();
}
});
mapFragment.getMapAsync(this);
mResultReceiver = new AddressResultReceiver(new Handler());
if (checkPlayServices()) {
// If this check succeeds, proceed with normal processing.
// Otherwise, prompt user to get valid Play Services APK.
if (!AppUtils.isLocationEnabled(mContext)) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setMessage("Location not enabled!");
dialog.setPositiveButton("Open location settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
buildGoogleApiClient();
} else {
Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "OnMapReady");
mMap = googleMap;
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
Log.d("Camera postion change" + "", cameraPosition + "");
mCenterLatLong = cameraPosition.target;
mMap.clear();
try {
Location mLocation = new Location("");
mLocation.setLatitude(mCenterLatLong.latitude);
mLocation.setLongitude(mCenterLatLong.longitude);
startIntentService(mLocation);
mLocationMarkerText.setText("Lat : " + mCenterLatLong.latitude + "," + "Long : " + mCenterLatLong.longitude);
} catch (Exception e) {
e.printStackTrace();
}
}
});
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
// mMap.setMyLocationEnabled(true);
// mMap.getUiSettings().setMyLocationButtonEnabled(true);
//
// // 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));
}
#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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
changeMap(mLastLocation);
Log.d(TAG, "ON connected");
} else
try {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
try {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
try {
if (location != null)
changeMap(location);
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
try {
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
try {
} catch (RuntimeException e) {
e.printStackTrace();
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
//finish();
}
return false;
}
return true;
}
private void changeMap(Location location) {
Log.d(TAG, "Reaching map" + mMap);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
// check if map is created successfully or not
if (mMap != null) {
mMap.getUiSettings().setZoomControlsEnabled(false);
LatLng latLong;
latLong = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build();
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
startIntentService(location);
} else {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
/**
* Receiver for data sent from FetchAddressIntentService.
*/
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
/**
* Receives data sent from FetchAddressIntentService and updates the UI in MainActivity.
*/
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Display the address string or an error message sent from the intent service.
mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);
mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);
mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);
displayAddressOutput();
// Show a toast message if an address was found.
if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
// showToast(getString(R.string.address_found));
}
}
}
/**
* Updates the address in the UI.
*/
protected void displayAddressOutput() {
// mLocationAddressTextView.setText(mAddressOutput);
try {
if (mAreaOutput != null)
// mLocationText.setText(mAreaOutput+ "");
mLocationAddress.setText(mAddressOutput);
//mLocationText.setText(mAreaOutput);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates an intent, adds location data to it as an extra, and starts the intent service for
* fetching an address.
*/
protected void startIntentService(Location mLocation) {
// Create an intent for passing to the intent service responsible for fetching the address.
Intent intent = new Intent(this, FetchAddressIntentService.class);
// Pass the result receiver as an extra to the service.
intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);
// Pass the location data as an extra to the service.
intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);
// Start the service. If the service isn't already running, it is instantiated and started
// (creating a process for it if needed); if it is running then it remains running. The
// service kills itself automatically once all intents are processed.
startService(intent);
}
private void openAutocompleteActivity() {
try {
// The autocomplete activity requires Google Play Services to be available. The intent
// builder checks this and throws an exception if it is not the case.
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(this);
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
} catch (GooglePlayServicesRepairableException e) {
// Indicates that Google Play Services is either not installed or not up to date. Prompt
// the user to correct the issue.
GoogleApiAvailability.getInstance().getErrorDialog(this, e.getConnectionStatusCode(),
0 /* requestCode */).show();
} catch (GooglePlayServicesNotAvailableException e) {
// Indicates that Google Play Services is not available and the problem is not easily
// resolvable.
String message = "Google Play Services is not available: " +
GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
}
/**
* Called after the autocomplete activity has finished to return its result.
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check that the result was from the autocomplete widget.
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
// Get the user's selected place from the Intent.
Place place = PlaceAutocomplete.getPlace(mContext, data);
// TODO call location based filter
LatLng latLong;
latLong = place.getLatLng();
//mLocationText.setText(place.getName() + "");
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(mContext, data);
} else if (resultCode == RESULT_CANCELED) {
// Indicates that the activity closed before a selection was made. For example if
// the user pressed the back button.
}
}
}
And manifest file is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample.sishin.maplocation">
<!--
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" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="your key here" />
<activity
android:name="com.sample.sishin.maplocation.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>
<service
android:name="com.sample.sishin.maplocation.FetchAddressIntentService"
android:exported="false" />
</application>
</manifest>

As LocationClient is deprected, I have used GoogleApiClient, Here is code for anyone who want to implement it.
Just Replacing LocationClient with GoogleApiClient else is same as #Sishin's code.
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Dialog;
import android.content.IntentSender.SendIntentException;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.app.anycabs.R;
import com.app.common.GPSTracker;
import com.app.modle.GData;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
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.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Stores the current instantiation of the location client in this object
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private TextView markerText;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_curent_locations);
markerText = (TextView) findViewById(R.id.locationMarkertext);
Address = (TextView) findViewById(R.id.adressText);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.curentlocationmapfragment)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
markerText.setText("Location received: "
+ location.toString());
}
});
Log.e("Reached", "here");
result.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e("Result", "success");
} else if (status.hasResolution()) {
// Google provides a way to fix the issue
try {
status.startResolutionForResult(MainActivity.this,
100);
} catch (SendIntentException e) {
e.printStackTrace();
}
}
}
});
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
markerText.setText(" Set your Location ");
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pin_last)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
Where GPSTracker is as below:
public class GPSTracker extends Service implements LocationListener {
private final FragmentActivity mActivity;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(FragmentActivity activity) {
this.mActivity = activity;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mActivity
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
locationManager = null;
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
if (mActivity == null || mActivity.isFinishing()) {
return;
}
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
mActivity);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("Your GPS is disabled, Enable GPS in settings or continue with approximate location");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mActivity.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
int which) {
// UserSerch doSerch = new UserSerch();
// doSerch.doserchOn();
// dialog.cancel();
}
});
// Showing Alert Message
alertDialog.create().show();
}
});
}
/**
* Get list of address by latitude and longitude
*
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
return addresses;
} catch (IOException e) {
// e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
e);
}
}
return null;
}
/**
* Try to get AddressLine
*
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
*
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
/**
* Try to get Postal Code
*
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
*
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
showSettingsAlert();
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I hope it will be helpful to anyone.

You can try out this example done by me....
Example done by me
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:name="com.rajeshvijayakumar.map.demo.ui.CustomMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include
android:id="#+id/marker_view_incl"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/marker_view" />
<include
android:id="#+id/location_display_incl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="7dp"
layout="#layout/location_display_view" />
</RelativeLayout>
marker_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/marker_icon_view"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerInParent="true"
android:layout_marginTop="162dp"
android:contentDescription="#string/app_name"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
location_display_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#android:color/white" >
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Set Location"
android:textColor="#android:color/holo_green_dark"
android:textSize="12sp" />
<TextView
android:id="#+id/location_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_view"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Set Location"
android:textColor="#android:color/black"
android:textSize="14sp" />
MapWrapperLayout.java
package com.rajeshvijayakumar.map.demo.wrapper;
public class MapWrapperLayout extends FrameLayout {
public interface OnDragListener {
public void onDrag(MotionEvent motionEvent);
}
private OnDragListener mOnDragListener;
public MapWrapperLayout(Context context) {
super(context);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mOnDragListener != null) {
mOnDragListener.onDrag(ev);
}
return super.dispatchTouchEvent(ev);
}
public void setOnDragListener(OnDragListener mOnDragListener) {
this.mOnDragListener = mOnDragListener;
}
}
CustomMapFragment.java
package com.rajeshvijayakumar.map.demo.ui;
public class CustomMapFragment extends MapFragment {
private View mOriginalView;
private MapWrapperLayout mMapWrapperLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mOriginalView = super.onCreateView(inflater, container, savedInstanceState);
mMapWrapperLayout = new MapWrapperLayout(getActivity());
mMapWrapperLayout.addView(mOriginalView);
return mMapWrapperLayout;
}
#Override
public View getView() {
return mOriginalView;
}
public void setOnDragListener(MapWrapperLayout.OnDragListener onDragListener) {
mMapWrapperLayout.setOnDragListener(onDragListener);
}
}
MainActivity.java
public class MainActivity extends Activity implements OnDragListener {
// Google Map
private GoogleMap googleMap;
private CustomMapFragment mCustomMapFragment;
private View mMarkerParentView;
private ImageView mMarkerImageView;
private int imageParentWidth = -1;
private int imageParentHeight = -1;
private int imageHeight = -1;
private int centerX = -1;
private int centerY = -1;
private TextView mLocationTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// InitializeUI
initializeUI();
}
private void initializeUI() {
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
mLocationTextView = (TextView) findViewById(R.id.location_text_view);
mMarkerParentView = findViewById(R.id.marker_view_incl);
mMarkerImageView = (ImageView) findViewById(R.id.marker_icon_view);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
imageParentWidth = mMarkerParentView.getWidth();
imageParentHeight = mMarkerParentView.getHeight();
imageHeight = mMarkerImageView.getHeight();
centerX = imageParentWidth / 2;
centerY = (imageParentHeight / 2) + (imageHeight / 2);
}
private void initilizeMap() {
if (googleMap == null) {
mCustomMapFragment = ((CustomMapFragment) getFragmentManager()
.findFragmentById(R.id.map));
mCustomMapFragment.setOnDragListener(MainActivity.this);
googleMap = mCustomMapFragment.getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,
// 10);
// googleMap.animateCamera(cameraUpdate);
// locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onDrag(MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
Projection projection = (googleMap != null && googleMap
.getProjection() != null) ? googleMap.getProjection()
: null;
//
if (projection != null) {
LatLng centerLatLng = projection.fromScreenLocation(new Point(
centerX, centerY));
updateLocation(centerLatLng);
}
}
}
private void updateLocation(LatLng centerLatLng) {
if (centerLatLng != null) {
Geocoder geocoder = new Geocoder(MainActivity.this,
Locale.getDefault());
List<Address> addresses = new ArrayList<Address>();
try {
addresses = geocoder.getFromLocation(centerLatLng.latitude,
centerLatLng.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String addressIndex0 = (addresses.get(0).getAddressLine(0) != null) ? addresses
.get(0).getAddressLine(0) : null;
String addressIndex1 = (addresses.get(0).getAddressLine(1) != null) ? addresses
.get(0).getAddressLine(1) : null;
String addressIndex2 = (addresses.get(0).getAddressLine(2) != null) ? addresses
.get(0).getAddressLine(2) : null;
String addressIndex3 = (addresses.get(0).getAddressLine(3) != null) ? addresses
.get(0).getAddressLine(3) : null;
String completeAddress = addressIndex0 + "," + addressIndex1;
if (addressIndex2 != null) {
completeAddress += "," + addressIndex2;
}
if (addressIndex3 != null) {
completeAddress += "," + addressIndex3;
}
if (completeAddress != null) {
mLocationTextView.setText(completeAddress);
}
}
}
}
}

GPSClass From #Shvet ans.
public class CarSelectActivity extends BaseActivity implements GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks {
private GoogleApiClient mGoogleApiClient;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
private GoogleMap mGoogleMap;
private ImageView mMarkerImageView;
private GPSTracker gps;
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
setContentView(R.layout.activit_carselect);
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
inilizviews();
}
private void inilizviews() {
gps = new GPSTracker(this);
mMarkerImageView = (ImageView) findViewById(R.id.im_marker);
}
#Override
public void onConnectionFailed(#NonNull final ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(final Location location) {
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.getUiSettings().isMyLocationButtonEnabled();
mGoogleMap.getUiSettings().isZoomControlsEnabled();
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
}
#Override
public void onConnected(#Nullable final Bundle bundle) {
mGoogleApiClient.connect();
setUpDragListners();
}
#Override
public void onConnectionSuspended(int i) {
}
private void setUpDragListners() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
gps.canGetLocation();
LatLng curentpoint = new LatLng(gps.getLatitude(), gps.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(15f).tilt(30).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
LatLng center = mGoogleMap.getCameraPosition().target;
try {
getLocation(center.latitude, center.longitude);
} catch (final Exception e) {
e.printStackTrace();
}
}
});
private void getLocation(double latitude, double longitude) {
Geocoder geocoder = new Geocoder(CarSelectActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
textView_places.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
}
}

Shorter Kotlin way:
wrap xml with Relative layout:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<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"
map:mapType="normal"
tools:context=".MapStartedActivity"/>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/imgLocationPinUp"
android:src="#drawable/location_pin_up"
/>
</RelativeLayout>
fun mapInit(googleMap: GoogleMap){
googleMap.apply {
// just a random location our map will point to when its launched
val klcc = LatLng(3.1579513, 101.7116233)
addMarker(MarkerOptions().apply {
position(klcc)
title("Marker pointed at klcc")
draggable(false)
})
// setup zoom level
animateCamera(CameraUpdateFactory.newLatLngZoom(klcc,18f))
// maps events we need to respond to
setOnCameraMoveListener(this#MapStartedActivity)
setOnCameraIdleListener(this#MapStartedActivity)
}
}
override fun onCameraMove() {
mMap.clear()
// display imageView
imgPinUp?.visibility = View.VISIBLE
}
override fun onCameraIdle() {
// hiding imageView
imgPinUp?.visibility = View.GONE
// customizing map marker with a custom icon
// and place it on the current map camera position
val markerOptions = MarkerOptions().position(mMap.cameraPosition.target)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_pin))
mMap.addMarker(markerOptions)
}

Related

Google Map not Displayed , Cannot get my LatLong

I need help. I have already set up Google Console in the right way, the right API and the right package name and SHA-1 for restricting usage in Android apps and I can see the green checkmark. In other words it worked before, but now the map in Google Map gone, just showing logo, my button and still can detect my LatLong.
My other problem is my Google Map can't show LatLong, my location button, and can't use mark if I turn off GPS. I need to turn ON the GPS outside of the activity. Even I make refresh button but still I need to turn on GPS outside of activity (like before get inside the map activity).
Here is my MapActivity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FloatingActionButton fabDone, fabRefresh;
private Location currentLocation;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Double MyLat, MyLong;
private String kode;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
Marker incidentMarker;
Geocoder geo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Intent intent = getIntent();
kode = intent.getStringExtra("kode");
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Map");
fabDone = findViewById(R.id.fab_done);
fabRefresh = findViewById(R.id.fab_refresh);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
geo = new Geocoder(getApplicationContext(), Locale.getDefault());
turnGPSOn();
fetchLocation();
fabRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
currentLocation = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled && currentLocation==null){
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
currentLocation = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (currentLocation != null) {
MyLat = currentLocation.getLatitude();
MyLong = currentLocation.getLongitude();
mMap.setMyLocationEnabled(true);
LatLng latLng = new LatLng(MyLat, MyLong);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else {
Location loc= getLastKnownLocation(this);
if (loc != null) {
MyLat = loc.getLatitude();
MyLong = loc.getLongitude();
mMap.setMyLocationEnabled(true);
LatLng latLng = new LatLng(MyLat, MyLong);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
}
}
locManager.removeUpdates(locListener);
try {
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
if (incidentMarker != null)
incidentMarker.remove();
MarkerOptions options = new MarkerOptions().position(latLng).title("Incident Location");
try {
Address address = geo.getFromLocation(latLng.latitude, latLng.longitude, 2).get(0);
String addressLine = address.getAddressLine(0); // If any additional
String snippets = addressLine;
Log.d("MAP", snippets);
options.snippet(snippets);
} catch (IOException e) {
e.printStackTrace();
}
incidentMarker = mMap.addMarker(options);
incidentMarker.showInfoWindow();
}
});
fabDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (incidentMarker == null) {
Toast.makeText(getApplicationContext(), "Points the incident location using Long Click!", Toast.LENGTH_SHORT).show();
return;
} else {
if (kode.equals("1")) {
Intent intent = new Intent(MapActivity.this, AddReportActivity.class);
intent.putExtra("address", incidentMarker.getSnippet());
intent.putExtra("latitude", incidentMarker.getPosition().latitude);
intent.putExtra("longitude", incidentMarker.getPosition().longitude);
startActivity(intent);
finish();//finishing activity
} else if (kode.equals("2")) {
Intent intent = new Intent(MapActivity.this, EditReportActivity.class);
intent.putExtra("address", incidentMarker.getSnippet());
intent.putExtra("latitude", incidentMarker.getPosition().latitude);
intent.putExtra("longitude", incidentMarker.getPosition().longitude);
startActivity(intent);
finish();//finishing activity
}
}
}
});
} catch (Exception e){e.printStackTrace();}
if (gps_enabled && network_enabled && currentLocation!=null){
MyLat = currentLocation.getLatitude();
MyLong = currentLocation.getLongitude();
mMap.setMyLocationEnabled(true);
LatLng latLng = new LatLng(MyLat, MyLong);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else if (gps_enabled && network_enabled && currentLocation==null){
Toast.makeText(this, "Location can't be found.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Please turn ON the GPS.", Toast.LENGTH_SHORT).show();
}
}
private void fetchLocation() {
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() + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fama_map);
assert supportMapFragment != null;
supportMapFragment.getMapAsync(MapActivity.this);
}
}
});
}
#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) {
fetchLocation();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_options, menu);
return true;
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public static Location getLastKnownLocation(Context context) {
Location location = null;
#SuppressLint("WrongConstant") LocationManager locationmanager = (LocationManager)context.getSystemService("location");
List list = locationmanager.getAllProviders();
boolean i = false;
Iterator iterator = list.iterator();
do
{
//System.out.println("---------------------------------------------------------------------");
if(!iterator.hasNext())
break;
String s = (String)iterator.next();
if(i != false && !locationmanager.isProviderEnabled(s))
continue;
#SuppressLint("MissingPermission") Location location1 = locationmanager.getLastKnownLocation(s);
if(location1 == null)
continue;
if(location != null)
{
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if(f >= f1)
{
long l = location1.getTime();
long l1 = location.getTime();
if(l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
// System.out.println("---------------------------------------------------------------------");
} while(true);
return location;
}
public void turnGPSOn(){
try
{
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
catch (Exception e) {
}
}
// Method to turn off the GPS
public void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
// turning off the GPS if its in on state. to avoid the battery drain.
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
turnGPSOff();
}
}
I Think this will help you. First see the package name is same you register on console
build.gradle
// google map services
implementation 'com.google.android.gms:play-services-maps:17.0.1'
// location play services
implementation 'com.google.android.gms:play-services-location:18.0.0'
// dexter runtime permissions
implementation 'com.karumi:dexter:4.2.0'
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
Java MapsActivity.java
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
TextView txtLocationResult;
TextView txtUpdatedOn;
Button btnStartUpdates;
Button btnStopUpdates;
// location last updated time
private String mLastUpdateTime;
// location updates interval - 10sec
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
// fastest updates interval - 5 sec
// location updates will be received if another app is requesting the locations
// than your app can handle
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 3000;
private static final int REQUEST_CHECK_SETTINGS = 100;
// bunch of location related apis
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private MarkerOptions marker;
private ArrayList<LatLng> locList;
// boolean flag to toggle the ui
private Boolean mRequestingLocationUpdates;
private String TAG = "MainActivity";
#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);
locList = new ArrayList();
marker = new MarkerOptions();
initViews();
initValues();
onClickMethod();
// restore the values from saved instance state
restoreValuesFromBundle(savedInstanceState);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng islamabad = new LatLng(33.684422, 73.047882);
mMap.setMinZoomPreference(15.0f);
mMap.setMaxZoomPreference(20.0f);
marker.position(islamabad);
mMap.addMarker(marker);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(islamabad, 17F));
}
private void mapDrawLocation(LatLng loc){
mMap.clear();
marker.position(loc);
mMap.addMarker(marker);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 17F));
}
private void initViews(){
txtLocationResult = findViewById(R.id.location_result);
txtUpdatedOn = findViewById(R.id.updated_on);
btnStartUpdates = findViewById(R.id.btn_start_location_updates);
btnStopUpdates = findViewById(R.id.btn_stop_location_updates);
}
private void onClickMethod(){
btnStartUpdates.setOnClickListener(view -> {
startLocationButtonClick();
});
btnStopUpdates.setOnClickListener(view -> {
stopLocationButtonClick();
});
}
private void initValues() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mSettingsClient = LocationServices.getSettingsClient(this);
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
// location is received
mCurrentLocation = locationResult.getLastLocation();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
}
};
mRequestingLocationUpdates = false;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
/**
* Restoring values from saved instance state
*/
private void restoreValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("is_requesting_updates")) {
mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates");
}
if (savedInstanceState.containsKey("last_known_location")) {
mCurrentLocation = savedInstanceState.getParcelable("last_known_location");
}
if (savedInstanceState.containsKey("last_updated_on")) {
mLastUpdateTime = savedInstanceState.getString("last_updated_on");
}
}
updateLocationUI();
}
/**
* Update the UI displaying the location data
* and toggling the buttons
*/
private void updateLocationUI() {
if (mCurrentLocation != null) {
txtLocationResult.setText(
"Lat: " + mCurrentLocation.getLatitude() + ", " +
"Lng: " + mCurrentLocation.getLongitude()
);
mapDrawLocation(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
// giving a blink animation on TextView
txtLocationResult.setAlpha(0);
txtLocationResult.animate().alpha(1).setDuration(300);
// location last updated time
txtUpdatedOn.setText("Last updated on: " + mLastUpdateTime);
}
toggleButtons();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("is_requesting_updates", mRequestingLocationUpdates);
outState.putParcelable("last_known_location", mCurrentLocation);
outState.putString("last_updated_on", mLastUpdateTime);
}
private void toggleButtons() {
if (mRequestingLocationUpdates) {
btnStartUpdates.setEnabled(false);
btnStopUpdates.setEnabled(true);
} else {
btnStartUpdates.setEnabled(true);
btnStopUpdates.setEnabled(false);
}
}
/**
* Starting location updates
* Check whether location settings are satisfied and then
* location updates will be requested
*/
private void startLocationUpdates() {
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#SuppressLint("MissingPermission")
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i(TAG, "All location settings are satisfied.");
Toast.makeText(getApplicationContext(), "Started location updates!", Toast.LENGTH_SHORT).show();
//noinspection MissingPermission
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
updateLocationUI();
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
"location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(MapsActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText(MapsActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
updateLocationUI();
}
});
}
public void startLocationButtonClick() {
// Requesting ACCESS_FINE_LOCATION using Dexter library
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
mRequestingLocationUpdates = true;
startLocationUpdates();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response.isPermanentlyDenied()) {
// open device settings when the permission is
// denied permanently
openSettings();
}
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
public void stopLocationButtonClick() {
mRequestingLocationUpdates = false;
stopLocationUpdates();
}
public void stopLocationUpdates() {
// Removing location updates
mFusedLocationClient
.removeLocationUpdates(mLocationCallback)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Location updates stopped!", Toast.LENGTH_SHORT).show();
toggleButtons();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.e(TAG, "User agreed to make required location settings changes.");
// Nothing to do. startLocationupdates() gets called in onResume again.
break;
case Activity.RESULT_CANCELED:
Log.e(TAG, "User chose not to make required location settings changes.");
mRequestingLocationUpdates = false;
break;
}
break;
}
}
private void openSettings() {
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
// Resuming location updates depending on button state and
// allowed permissions
if (mRequestingLocationUpdates && checkPermissions()) {
startLocationUpdates();
}
updateLocationUI();
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
#Override
protected void onPause() {
super.onPause();
if (mRequestingLocationUpdates) {
// pausing location updates
stopLocationUpdates();
}
}
}
activity_maps.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
tools:context=".MapsActivity"
map:layout_constraintBottom_toTopOf="#+id/bottom_panel"
map:layout_constraintTop_toTopOf="parent"
/>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/bottom_panel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
map:layout_constraintBottom_toBottomOf="parent"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toEndOf="parent"
>
<TextView
android:id="#+id/location_result"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="#333"
android:textSize="18sp"
android:gravity="center"
android:text="Lat: 0.0, Lng: 0.0"
android:layout_gravity="center"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="#+id/updated_on"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="12sp"
android:gravity="center"
android:layout_gravity="center"
android:text="Last updated on: "
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintTop_toBottomOf="#+id/location_result"
/>
<Button
android:id="#+id/btn_start_location_updates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="START LOCATION"
map:layout_constraintTop_toBottomOf="#+id/updated_on"
map:layout_constraintBottom_toBottomOf="parent"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toStartOf="#+id/btn_stop_location_updates"
/>
<Button
android:id="#+id/btn_stop_location_updates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:enabled="false"
android:text="STOP LOCATION"
map:layout_constraintTop_toBottomOf="#+id/updated_on"
map:layout_constraintStart_toEndOf="#+id/btn_start_location_updates"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintBottom_toBottomOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
I Think this will help you. First see the package name is same you register on console
build.gradle
// google map services
implementation 'com.google.android.gms:play-services-maps:17.0.1'
// location play services
implementation 'com.google.android.gms:play-services-location:18.0.0'
// dexter runtime permissions
implementation 'com.karumi:dexter:4.2.0'
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
Kotlin MapsActivity.kt
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.Location
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
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.*
import com.karumi.dexter.BuildConfig
import com.karumi.dexter.Dexter
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.single.PermissionListener
import java.text.DateFormat
import java.util.*
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
// location last updated time
private var mLastUpdateTime: String? = null
// location updates interval - 10sec
private val UPDATE_INTERVAL_IN_MILLISECONDS: Long = 10000
// fastest updates interval - 5 sec
// location updates will be received if another app is requesting the locations
// than your app can handle
private val FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS: Long = 3000
private val REQUEST_CHECK_SETTINGS = 100
private val TAG = "MainActivity"
private lateinit var mMap: GoogleMap
// bunch of location related apis
private var mFusedLocationClient: FusedLocationProviderClient? = null
private var mSettingsClient: SettingsClient? = null
private var mLocationRequest: LocationRequest? = null
private var mLocationSettingsRequest: LocationSettingsRequest? = null
private var mLocationCallback: LocationCallback? = null
private var mCurrentLocation: Location? = null
// boolean flag to toggle the ui
private var mRequestingLocationUpdates: Boolean? = null
private lateinit var txtLocationResult: TextView
private lateinit var txtUpdatedOn: TextView
private lateinit var btnStartUpdates: Button
private lateinit var btnStopUpdates: Button
private var marker:MarkerOptions? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
// initialize the necessary libraries
initViews()
initValues()
onClickMethod()
// restore the values from saved instance state
restoreValuesFromBundle(savedInstanceState)
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
// Add a marker in Sydney and move the camera
val islamabad = LatLng(33.684422, 73.047882)
mMap.setMinZoomPreference(15.0f)
mMap.setMaxZoomPreference(20.0f)
marker?.position(islamabad)
mMap.addMarker(marker!!)
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(islamabad, 17F))
}
private fun mapDrawLocation(loc:LatLng){
mMap.clear()
marker?.position(loc)
mMap.addMarker(marker!!)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 17F))
}
private fun initViews(){
txtLocationResult = findViewById(R.id.location_result)
txtUpdatedOn = findViewById(R.id.updated_on)
btnStartUpdates = findViewById(R.id.btn_start_location_updates)
btnStopUpdates = findViewById(R.id.btn_stop_location_updates)
}
private fun initValues() {
marker = MarkerOptions()
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
mSettingsClient = LocationServices.getSettingsClient(this)
mLocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
// location is received
mCurrentLocation = locationResult.lastLocation
mLastUpdateTime = DateFormat.getTimeInstance().format(Date())
updateLocationUI()
}
}
mRequestingLocationUpdates = false
mLocationRequest = LocationRequest.create().apply {
interval = UPDATE_INTERVAL_IN_MILLISECONDS
fastestInterval = FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
isWaitForAccurateLocation = true
}
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(mLocationRequest!!)
mLocationSettingsRequest = builder.build()
}
private fun onClickMethod(){
btnStartUpdates.setOnClickListener {
startLocationButtonClick()
}
btnStopUpdates.setOnClickListener {
stopLocationButtonClick()
}
}
/**
* Restoring values from saved instance state
*/
private fun restoreValuesFromBundle(savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("is_requesting_updates")) {
mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates")
}
if (savedInstanceState.containsKey("last_known_location")) {
mCurrentLocation = savedInstanceState.getParcelable("last_known_location")
}
if (savedInstanceState.containsKey("last_updated_on")) {
mLastUpdateTime = savedInstanceState.getString("last_updated_on")
}
}
updateLocationUI()
}
/**
* Update the UI displaying the location data
* and toggling the buttons
*/
#SuppressLint("SetTextI18n")
private fun updateLocationUI() {
if (mCurrentLocation != null) {
txtLocationResult.text = "Lat: " + mCurrentLocation!!.latitude + ", " +
"Lng: " + mCurrentLocation!!.longitude
mapDrawLocation(LatLng(mCurrentLocation!!.latitude, mCurrentLocation!!.longitude))
// giving a blink animation on TextView
txtLocationResult.alpha = 0f
txtLocationResult.animate().alpha(1f).duration = 300
// location last updated time
txtUpdatedOn.text = "Last updated on: $mLastUpdateTime"
}
toggleButtons()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("is_requesting_updates", (mRequestingLocationUpdates)!!)
outState.putParcelable("last_known_location", mCurrentLocation)
outState.putString("last_updated_on", mLastUpdateTime)
}
private fun toggleButtons() {
if ((mRequestingLocationUpdates)!!) {
btnStartUpdates.isEnabled = false
btnStopUpdates.isEnabled = true
} else {
btnStartUpdates.isEnabled = true
btnStopUpdates.isEnabled = false
}
}
/**
* Starting location updates
* Check whether location settings are satisfied and then
* location updates will be requested
*/
private fun startLocationUpdates() {
mSettingsClient
?.checkLocationSettings(mLocationSettingsRequest!!)
?.addOnSuccessListener(this) {
Log.i(TAG, "All location settings are satisfied.")
showMessage("Started location updates!")
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
}
mFusedLocationClient!!.requestLocationUpdates(
mLocationRequest!!,
mLocationCallback!!, Looper.myLooper()!!
)
updateLocationUI()
}
?.addOnFailureListener(this) { e ->
val statusCode = (e as ApiException).statusCode
when (statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
Log.i(
TAG,
"Location settings are not satisfied. Attempting to upgrade " +
"location settings "
)
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
val rae = e as ResolvableApiException
rae.startResolutionForResult(
this,
REQUEST_CHECK_SETTINGS
)
} catch (sie: IntentSender.SendIntentException) {
Log.i(
TAG,
"PendingIntent unable to execute request."
)
}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
val errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings."
Log.e(TAG, errorMessage)
}
}
updateLocationUI()
}
}
private fun startLocationButtonClick() {
// Requesting ACCESS_FINE_LOCATION using Dexter library
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(object : PermissionListener {
override fun onPermissionGranted(response: PermissionGrantedResponse?) {
mRequestingLocationUpdates = true
startLocationUpdates()
}
override fun onPermissionDenied(response: PermissionDeniedResponse) {
if (response.isPermanentlyDenied) {
// open device settings when the permission is
// denied permanently
openSettings()
}
}
override fun onPermissionRationaleShouldBeShown(
permission: PermissionRequest?,
token: PermissionToken
) {
token.continuePermissionRequest()
}
}).check()
}
private fun stopLocationButtonClick() {
mRequestingLocationUpdates = false
stopLocationUpdates()
}
private fun stopLocationUpdates() {
// Removing location updates
mFusedLocationClient
?.removeLocationUpdates(mLocationCallback!!)
?.addOnCompleteListener(this) {
showMessage("Location updates stopped!")
toggleButtons()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_CHECK_SETTINGS -> when (resultCode) {
RESULT_OK -> Log.e(
TAG,
"User agreed to make required location settings changes."
)
RESULT_CANCELED -> {
Log.e(
TAG,
"User chose not to make required location settings changes."
)
mRequestingLocationUpdates = false
}
}
}
}
override fun onResume() {
super.onResume()
// Resuming location updates depending on button state and
// allowed permissions
if ((mRequestingLocationUpdates)!! && checkPermissions()) {
startLocationUpdates()
}
updateLocationUI()
}
private fun checkPermissions(): Boolean {
val permissionState = ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
return permissionState == PackageManager.PERMISSION_GRANTED
}
override fun onPause() {
super.onPause()
if ((mRequestingLocationUpdates)!!) {
// pausing location updates
stopLocationUpdates()
}
}
private fun openSettings() {
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts(
"package",
BuildConfig.APPLICATION_ID, null
)
intent.data = uri
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
private fun showMessage(message:String){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show()
}
}
activity_maps.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
tools:context=".MapsActivity"
map:layout_constraintBottom_toTopOf="#+id/bottom_panel"
map:layout_constraintTop_toTopOf="parent"
/>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/bottom_panel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
map:layout_constraintBottom_toBottomOf="parent"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toEndOf="parent"
>
<TextView
android:id="#+id/location_result"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="#333"
android:textSize="18sp"
android:gravity="center"
android:text="Lat: 0.0, Lng: 0.0"
android:layout_gravity="center"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="#+id/updated_on"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="12sp"
android:gravity="center"
android:layout_gravity="center"
android:text="Last updated on: "
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintTop_toBottomOf="#+id/location_result"
/>
<Button
android:id="#+id/btn_start_location_updates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="START LOCATION"
map:layout_constraintTop_toBottomOf="#+id/updated_on"
map:layout_constraintBottom_toBottomOf="parent"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintEnd_toStartOf="#+id/btn_stop_location_updates"
/>
<Button
android:id="#+id/btn_stop_location_updates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:enabled="false"
android:text="STOP LOCATION"
map:layout_constraintTop_toBottomOf="#+id/updated_on"
map:layout_constraintStart_toEndOf="#+id/btn_start_location_updates"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintBottom_toBottomOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

GPS Locations Android

I have created a project sunshine which gives weathery detail by tracking your
current location it works fine but sometimes my GPSTracker class which returns me the latitude,longitude and postal code along with the country doesnt return the data at the time and then my app shows then the network error
I dont know whats the problem sometimes it works very fine but sometimes it doesnt.
My GPSTracker class:-
package com.example.na462.sunshine;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
GPSEnabled.GPS = isGPSEnabled;
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
int afl = ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION );
int acl = ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION );
if (locationManager != null) {
Log.d("locationManager",""+locationManager);
if (afl != PackageManager.PERMISSION_GRANTED && acl != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return location;
}
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle("Alert Title");
//Setting Dialog Message
alertDialog.setMessage("gpsmessage");
//On Pressing Setting button
alertDialog.setPositiveButton(0, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton("cancle", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
*
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
return addresses;
} catch (IOException e) {
// e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
e);
}
}
return null;
}
/**
* Try to get AddressLine
*
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
*
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
/**
* Try to get Postal Code
*
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
*
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And my Splash Activity where i am demanding for postal code and other stuff:
Note ValuetoPass,Coordinates and CordinateLoc are other classes in other activitites for passing the information i have used them
package com.example.na462.sunshine;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URL;
import static android.R.attr.animation;
import static com.example.na462.sunshine.R.id.MainList;
public class SplashActivity extends Activity implements Animation.AnimationListener {
Animation animation,TextAnimation;
Double Latitude;
Double Longitude;
String Country;
ImageView imageView;
ImageView ErrorImage;
TextView AnimationText;
Button ErrorReload;
LinearLayout Layout;
String PostalCode;
Receiver receiver;
boolean Connection;
GPSTracker gpsTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
AnimationText = (TextView)findViewById(R.id.TextAnimation);
ErrorReload = (Button)findViewById(R.id.ErrorReload);
imageView = (ImageView)(SplashActivity.this).findViewById(R.id.Animation);
Layout = (LinearLayout)findViewById(R.id.Error);
ErrorImage = (ImageView)findViewById(R.id.Nointernet);
gpsTracker = new GPSTracker(SplashActivity.this);
gpsTracker.getLocation();
receiver = new Receiver();
Connection = receiver.internetconnection(SplashActivity.this);
if(!Connection || !GPSEnabled.GPS){
imageView.setVisibility(View.INVISIBLE);
Layout.setVisibility(View.VISIBLE);
ErrorImage.setVisibility(View.VISIBLE);
AnimationText.setVisibility(View.INVISIBLE);
}
else {
AnimationText.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
Layout.setVisibility(View.INVISIBLE);
ErrorImage.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(SplashActivity.this, ScrollingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
}, 8000);
animation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animation.setAnimationListener(this);
imageView.startAnimation(animation);
TextAnimation = AnimationUtils.loadAnimation(this,R.anim.blink);
TextAnimation.setAnimationListener(this);
AnimationText.startAnimation(TextAnimation);
new FetchGPS().execute();
}
}
private class FetchGPS extends AsyncTask<Void,Void,String>{
#Override
protected String doInBackground(Void... voids) {
Latitude = gpsTracker.getLatitude();
Longitude = gpsTracker.getLongitude();
Country = gpsTracker.getCountryName(SplashActivity.this);
PostalCode = gpsTracker.getPostalCode(SplashActivity.this);
CordinatesLoc.Latitude = Latitude;
CordinatesLoc.Longitude = Longitude;
CordinatesLoc.CLatitude = Latitude;
CordinatesLoc.CLongitude = Longitude;
CordinatesLoc.Country = Country;
Coordinates.Latitude = String.valueOf(Latitude);
Coordinates.Longitude = String.valueOf(Longitude);
CordinatesLoc.Postal = PostalCode;
ValuesToPass.Pincode = PostalCode;
ValuesToPass.Country = "in";
return PostalCode;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
// Its an onclick Method For Retry if there isnt any conncection or GPS Estabished
public boolean ErrorReload(View V){
imageView.setVisibility(View.INVISIBLE);
Layout.setVisibility(View.INVISIBLE);
AnimationText.setVisibility(View.INVISIBLE);
ErrorImage.setVisibility(View.INVISIBLE);
gpsTracker.getLocation();
Connection = receiver.internetconnection(SplashActivity.this);
if(!Connection || !GPSEnabled.GPS){
imageView.setVisibility(View.INVISIBLE);
Layout.setVisibility(View.VISIBLE);
ErrorImage.setVisibility(View.VISIBLE);
return false;
}
AnimationText.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
Layout.setVisibility(View.INVISIBLE);
ErrorImage.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(SplashActivity.this, ScrollingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
}, 8000);
animation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animation.setAnimationListener(this);
imageView.startAnimation(animation);
TextAnimation = AnimationUtils.loadAnimation(this,R.anim.blink);
TextAnimation.setAnimationListener(this);
AnimationText.startAnimation(TextAnimation);
new FetchGPS().execute();
return true;
}
}
I think you should check your manifest.mf file. Maybe you need to add a permission to locate your smartphone.
i think code works fine...sometimes GPS cannot track coordinates in buildings. best solution is to use fused location provider api

Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER

I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :
private void getLocation() {
try {
if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Constant.displayLogE(">> PErmission >> ", ">> not granted");
return;
} else {
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0,
0, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mCurrentLatitude = mLocation.getLatitude();
mCurrentLongitude = mLocation.getLongitude();
loadFilterListData();
}
}
} else if (isGPSEnabled) {
if (mLocation == null) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mCurrentLatitude = mLocation.getLatitude();
mCurrentLongitude = mLocation.getLongitude();
loadFilterListData();
}
}
}
}
if (mLocation == null) {
Constant.displayToast(mContext, "Location not fetched. Please, try again.");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.
I have given necessary permissions in my Manifest file also.
What might be the issue ?
Thanks.
This is my MapsActivity class with location updates, you can update your code using my code
package com.example.vishal.gpsloc;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
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.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 org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.vision.barcode.Barcode;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, com.google.android.gms.location.LocationListener, GoogleMap.OnMapClickListener, ResultCallback<Status> {
GoogleMap mMap;
private MarkerOptions marker1, marker2;
private final int GEOFENCE_REQ_CODE = 0;
private GoogleApiClient googleApiClient;
private double longitude;
private double latitude;
double lat,lon;
List latt=new ArrayList();
List longi=new ArrayList();
Location lastLocation;
String ip=null;
SharedPreferences pref;
SharedPreferences.Editor editor;
int flag=1;String cityName,stateName,countryName,root;
private ArrayList<LatLng> points; //added
Polyline line; //added
File log,myDir;
private static MQTT mqtt;
private static BlockingConnection connection;
private final int UPDATE_INTERVAL = 60000 ;
private final int FASTEST_INTERVAL = 60000 ;
private static final float SMALLEST_DISPLACEMENT = 0.25F; //quarter of a meter
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()), cord, devname, devid = android.os.Build.SERIAL;
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
CheckConnection();
if (!isGooglePlayServicesAvailable()) {
System.out.println(" My Google Play Not Available");
finish();
}
points = new ArrayList<LatLng>(); //added
setContentView(R.layout.route_mapper);
// 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);
InitializeDB();
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PunchStop();
}
});
if (this.mMap != null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
mMap.setMyLocationEnabled(true);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
mqtt=new MQTT();
try{
if(ip==null){
System.out.println("Mqtt Initialized in Maps Activity");
ip="demo.aiotm.in:1883";
}
//mqtt.setHost("tcp://"+ip);
mqtt.setHost("tcp://10.30.60.242:1883");
connection = mqtt.blockingConnection();
connection.connect();
}catch (Exception e){
e.printStackTrace();
}
}
private void InitializeDB() {
pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
editor = pref.edit();
if (isExternalStorageReadable() == true && isExternalStorageWritable() == true) {
root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/GpsTracking");
myDir.mkdirs();
log = new File (myDir, "GpsLog");
if (myDir.exists()) {
System.out.println("Directory Already Exsists............");
} else {
try {
myDir = new File(root + "/GpsTracking");
myDir.mkdirs();
log = new File (myDir, "GpsLog");
} catch (Exception e) {
Toast.makeText(getBaseContext()
,e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}else {Toast.makeText(getBaseContext(),
"Permissions Not Availiable'",
Toast.LENGTH_SHORT).show();}
}
private void PunchStop() {
System.out.println("stop Location is "+latitude+","+longitude+"\t"+cityName );
try {
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
PrintWriter out = new PrintWriter(new FileWriter(log, true));
out.append(currentDateTimeString+"\t"+latitude+","+longitude+"\t"+cityName+"\n");
out.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'GpsLog.txt'",
Toast.LENGTH_SHORT).show();
}catch (Exception e){e.printStackTrace();}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
private void CheckConnection() {
String answer=null;
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
answer="You are connected to a WiFi Network";
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
answer="You are connected to a Mobile Network";
}
else
answer = "No internet Connectivity";
Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG).show();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
getCurrentLocation();
mMap.setOnMapLongClickListener(this);
mMap.setOnMapClickListener(this);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_POWER ) {
//Handle what you want in long press.
Toast.makeText(getApplicationContext(),"Power Key Pressed",Toast.LENGTH_LONG).show();
flag=1;
return true;
}
return super.onKeyLongPress(keyCode, event);
}
private void getCurrentLocation() {
//mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
System.out.println("Parameters are ::" + latitude + ":" + longitude);
//moving the map to location
moveMap();
}
}
private void moveMap() {
/**
* Creating the latlng object to store lat, long coordinates
* adding marker to map
* move the camera with animation
*/
LatLng latLng = new LatLng(latitude, longitude);
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
addresses = geocoder.getFromLocation(latitude, longitude, 1);
cityName = addresses.get(0).getAddressLine(0);
stateName = addresses.get(0).getAddressLine(1);
countryName = addresses.get(0).getAddressLine(2);
} catch (IOException e) {
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
.draggable(true)
.title(cityName))
.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i("info", "Connection Failed");
try {
// connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Toast.makeText(MapsActivity.this, "Connected", Toast.LENGTH_SHORT).show();
getCurrentLocation();
Log.i("info", "onConnected()");
getLastKnownLocation();
}
private void getLastKnownLocation() {
Log.d("INFO", "getLastKnownLocation()");
System.out.println("info :: getLastKnownLocation");
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
Log.i("INFO", "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w("INFO", "No location retrieved yet");
startLocationUpdates();
}
}
private LocationRequest locationRequest;
// Start location Updatess
private void startLocationUpdates() {
Log.i("INFO", "startLocationUpdates()");
pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
editor = pref.edit();
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setSmallestDisplacement(SMALLEST_DISPLACEMENT)
.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
marker1 = null;
marker2 = null;
getCurrentLocation();
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
public void onMapClick(LatLng latLng) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("INFO", "onLocationChanged ["+location+"]");
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
cityName = addresses.get(0).getAddressLine(0);
stateName = addresses.get(0).getAddressLine(1);
countryName = addresses.get(0).getAddressLine(2);
} catch (IOException e) {
e.printStackTrace();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title(cityName))
.showInfoWindow();
points.add(latLng);
redrawline();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
lastLocation = location;
writeActualLocation(location);
}
private void redrawline() {
mMap.clear(); //clears all Markers and Polylines
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int i = 0; i < points.size(); i++) {
LatLng point = points.get(i);
options.add(point);
}
getCurrentLocation(); //add Marker in current position
line = mMap.addPolyline(options); //add Polyline
}
// Write location coordinates on UI
private void writeActualLocation(Location location) {
Log.d( "Actual Lat: ", String.valueOf(location.getLatitude()));
Log.d( "Actual Long: ", String.valueOf(location.getLongitude()));
lat=location.getLatitude();
lon=location.getLongitude();
LatLng latLng=new LatLng(lat,lon);
mMap.addMarker(new MarkerOptions()
.position(latLng));
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
#Override
public void onResult(#NonNull Status status) {
Log.i("INFO", "onResult: " + status);
if ( status.isSuccess() ) {
System.out.println("Status Succes");
Toast.makeText(getApplicationContext(),"Status Succes",Toast.LENGTH_LONG).show();
// drawGeofence();
} else {
System.out.println("Status failed");
Toast.makeText(getApplicationContext(),"Status Failed",Toast.LENGTH_LONG).show();
}
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
}
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0,
0, this); // 'this' is onLocationChanged()
#Override
public void onLocationChanged(Location location) {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
}
User has to on the location service manually. Here is the code.Use the following method to turn on location services. Also place manifest permissions
public void checkLocationService() {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("GPS Not Enabled");
dialog.setCancelable(false);
dialog.setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Skip", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
Permissions:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
as JayDeep Patel referenced me for the Answer,
I have used fused google api , to get the accurate location inside my onConnected() method as below : (got success :))
pls. check it out : its really works :
private void getLocation() {
try {
if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Constant.displayLogE(">> PErmission >> ", ">> not granted");
return;
} else {
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0,
0, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mCurrentLatitude = mLocation.getLatitude();
mCurrentLongitude = mLocation.getLongitude();
loadFilterListData();
} else {
mCurrentLatitude = mLastLocation.getLatitude();
mCurrentLongitude = mLastLocation.getLongitude();
loadFilterListData();
}
}
} else if (isGPSEnabled) {
if (mLocation == null) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mCurrentLatitude = mLocation.getLatitude();
mCurrentLongitude = mLocation.getLongitude();
loadFilterListData();
} else {
mCurrentLatitude = mLastLocation.getLatitude();
mCurrentLongitude = mLastLocation.getLongitude();
loadFilterListData();
}
}
}
}
if (mLastLocation == null) {
Constant.displayToast(mContext, "Location not fetched. Please, try again.");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
and below is my onConnected() method :
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// here we go you can see current lat long.
Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude()));
}
}
Try GoogleApiClient to get user Current Location
Sample Code:
First you need to build a connection to googleApiclient
private synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(YourApplication.getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
Ask for Permission for Android 6.0 and above version
public void checkLocationPermission(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
// You don't have the permission you need to request it
ActivityCompat.requestPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION), REQ_CODE);
}else{
// You have the permission.
requestLocationAccess();
}
}
Then implement onRequestPermissionResult to check that user granted permission or not
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
requestLocationAccess();
} else {
Snackbar.make(findViewById(android.R.id.content), "Please Allow to access to your Location",
Snackbar.LENGTH_LONG).setAction("Allow",
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
}).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Create method requestLocationAccess where you will access location
public void requestLocationAccess(){
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval((long) (LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS*1.1));
mLocationRequest.setFastestInterval(LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
final LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
com.google.android.gms.common.api.PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
#Override
public void onResult(#NonNull LocationSettingsResult result){
if(requester != null){
final Status resultStatus = result.getStatus();
switch(resultStatus.getStatusCode()){
case LocationSettingsStatusCodes.SUCCESS:
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, YourActivity.this);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user a dialog.
ActivityCompat.requestPermissions(YourActivity.this, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
try{
resultStatus.startResolutionForResult(this, REQUEST_LOCATION);
break;
}catch(IntentSender.SendIntentException ignored){}
}
}
}
}
});
}
Then implement GoogleApliClient callback onConnected where you can get user location simply
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ContextCompat
.checkSelfPermission(this,
ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(
googleApiClient);
}
}

Add Google Places items into ListView

I am implementing an application that shows the nearest restaurants. I want to have two activities, one to show the restaurants in a map, and the other one to show in a ListView.
This is the code to retrieve the data an add markers.
public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {
String googlePlacesData;
GoogleMap mMap;
String url;
#Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadUrl downloadUrl = new DownloadUrl();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlaceData", googlePlacesData);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}
#Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
Log.d("List of restaurants",nearbyPlacesList.toString());
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
}
The code that parses the data:
public class DataParser {
public List<HashMap<String, String>> parse(String jsonData) {
JSONArray jsonArray = null;
JSONObject jsonObject;
try {
Log.d("Places", "parse");
jsonObject = new JSONObject(jsonData);
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
Log.d("Places", "parse error");
e.printStackTrace();
}
return getPlaces(jsonArray);
}
private List<HashMap<String, String>> getPlaces(JSONArray jsonArray) {
int placesCount = jsonArray.length();
List<HashMap<String, String>> placesList = new ArrayList<>();
HashMap<String, String> placeMap = null;
Log.d("Places", "getPlaces");
for (int i = 0; i < placesCount; i++) {
try {
placeMap = getPlace((JSONObject) jsonArray.get(i));
placesList.add(placeMap);
Log.d("Places", "Adding places");
} catch (JSONException e) {
Log.d("Places", "Error in Adding places");
e.printStackTrace();
}
}
return placesList;
}
private HashMap<String, String> getPlace(JSONObject googlePlaceJson) {
HashMap<String, String> googlePlaceMap = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
Log.d("getPlace", "Entered");
try {
if (!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name");
}
if (!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity");
}
latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = googlePlaceJson.getString("reference");
googlePlaceMap.put("place_name", placeName);
googlePlaceMap.put("vicinity", vicinity);
googlePlaceMap.put("lat", latitude);
googlePlaceMap.put("lng", longitude);
googlePlaceMap.put("reference", reference);
Log.d("getPlace", "Putting Places");
} catch (JSONException e) {
Log.d("getPlace", "Error");
e.printStackTrace();
}
return googlePlaceMap;
}
}
This is for the HTTPConnection:
public class DownloadUrl {
public String readUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
This is what I have tried to do to retrieve the response:
public class ListRestActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetNearbyPlacesData().execute();
}
}
EDIT
Added activity that retrieves my latitude and longitude and constructs my url:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
// 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);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
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);
}
String Restaurant = "restaurant";
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
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);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
//Place current location marker
latitude = 45.772;
longitude = 21.219;
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "-");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
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_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
Logcat:
1-16 16:18:12.101 4224-4224/com.upt.cti.nearbyrestaurant E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.upt.cti.nearbyrestaurant.DataParser.parse(DataParser.java:25)
at com.upt.cti.nearbyrestaurant.GetNearbyPlacesData.onPostExecute(GetNearbyPlacesData.java:46)
at com.upt.cti.nearbyrestaurant.GetNearbyPlacesData.onPostExecute(GetNearbyPlacesData.java:19)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4963)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
I get a NullpointerException. Is this not enough ? Could somebody help me ?
I used great tutorial from Androidhive, link here. Did you check, do you get something in onPostExecute as a result ? Where it become null, on parsing or on retrieving?
Maps Activity.java
package com.android.trainee.activity;
import android.Manifest;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.android.trainee.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsStatusCodes;
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.CameraPosition;
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 java.util.ArrayList;
import java.util.List;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
private GoogleApiClient googleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private final int[] MAP_TYPES = {GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID,
GoogleMap.MAP_TYPE_TERRAIN,
GoogleMap.MAP_TYPE_NONE};
private int curMapTypeIndex = 1;
int REQUEST_CHECK_SETTINGS = 100;
Marker currLocationMarker;
MarkerOptions markerOptions;
String result;
View mapView;
ListView simpleList;
ArrayList<String> aa = new ArrayList<String>();
#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);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
simpleList = (ListView) findViewById(R.id.simpleListView);
}
private void gps() {
if (googleApiClient == null) {
googleApiClient = new
GoogleApiClient.Builder(getApplicationContext())
.addApi(LocationServices.API).build();
googleApiClient.connect();
location();
}
}
private void location() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(100);
LocationSettingsRequest.Builder builder = new
LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(false); // this is the key ingredient
PendingResult result = LocationServices.SettingsApi.
checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback() {
#Override
public void onResult(#NonNull Result result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(MapsActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "GPS enabled",
Toast.LENGTH_LONG).show();
} else {
location();
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the
camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be
prompted to install
* it inside the SupportMapFragment. This method will only be triggered once
the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
gps();
mGoogleMap = googleMap;
mGoogleMap.setMapType(MAP_TYPES[curMapTypeIndex]);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mGoogleMap.setMyLocationEnabled(true);
// mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setOnMapClickListener(new
GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
//save current location
getAddress(latLng);
location(latLng);
}
});
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View)
mapView.findViewById(Integer.parseInt("1"))
.getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 30, 30);
}
mGoogleMap.setOnCameraChangeListener(new
GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(final CameraPosition
cameraPosition) {
mGoogleMap.setOnMapLoadedCallback(new
GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng =
mGoogleMap.getCameraPosition().target;
getAddress(latLng);
}
});
}
});
} else {
//Request Location Permission
gps();
}
} else {
mGoogleMap.setMyLocationEnabled(true);
// mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
{
#Override
public void onMapClick(LatLng latLng) {
//save current location
getAddress(latLng);
location(latLng);
}
});
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View)
mapView.findViewById(Integer.parseInt("1"))
.getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 30, 30);
}
mGoogleMap.setOnCameraChangeListener(new
GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(final CameraPosition cameraPosition)
{
mGoogleMap.setOnMapLoadedCallback(new
GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng =
mGoogleMap.getCameraPosition().target;
getAddress(latLng);
}
});
}
});
}
}
public void location(LatLng latLng) {
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(result);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
currLocationMarker = mGoogleMap.addMarker(markerOptions);
}
public List<Address> getAddress(LatLng latLng) {
try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this);
if (latLng.latitude != 0 || latLng.longitude != 0) {
addresses = geocoder.getFromLocation(latLng.latitude,
latLng.longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
Toast.makeText(this, address + " - " + city + " - " + country,
Toast.LENGTH_LONG).show();
aa.add(address + city + country);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, R.layout.activity_listview, R.id.textView, aa);
simpleList.setAdapter(arrayAdapter);
return addresses;
} else {
Toast.makeText(this, "latitude and longitude are null",
Toast.LENGTH_LONG).show();
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
// gpsTreker();
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(googleApiClient,
mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#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_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
}
}
activity_maps.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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="360dp"
tools:context="com.android.trainee.activity.MapsActivity">
</fragment>
<ListView
android:id="#+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:divider="#cfc4c4"
android:dividerHeight="1dp"/>
</LinearLayout>
</ScrollView>
activity_listview. xml
<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/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="#dimen/activity_horizontal_margin"
android:textColor="#color/colorPrimaryDarktab" />
</LinearLayout>
android manifast.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.trainee">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<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" />
<!--
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-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- <uses-permission android:name="android.permission.ACCESS_FINE_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/Theme.AppCompat.Light.NoActionBar">
<activity
android:name=".activity.HomeSplashActivity"
android:launchMode="singleInstance"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activity.SignUpActivity" />
<activity android:name=".activity.LoginActivity" />
<activity
android:name=".activity.DashBoard"
android:label="#string/title_activity_dash_board"
android:theme="#style/Theme.AppCompat.Light.NoActionBar" />
<activity android:name=".activity.ProfileActivity" />
<activity android:name=".activity.Contects" />
<!--
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=".activity.MapsActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_maps" />
<activity android:name=".activity.BackgroundServices"></activity>
<service android:name=".services.MediaService" />
</application>
</manifest>``

Current Location Background service is not working

I need to get Current Location from my Service class & pass the recently get values to the activity class.But using, this class I can not get Current location's lattitude & longitude. Here is my code.Please check it.
Service Class:
public class MyLocation extends Service {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
Context con;
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
if (ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
if (ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
public boolean getLocation(Context context, LocationResult result) {
con = context;
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
//don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if (network_enabled)
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return network_enabled;
}
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
if (ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
}
Please try to get current location lat lng using this GPSTracker.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;// flag for GPS status
boolean isNetworkEnabled = false;// flag for network status
boolean canGetLocation = false;// flag for GPS status
Location location; // location
double latitude; // latitude
double longitude; // longitude
/* How many GeoCoder should return our GPSTracker */
int geocoderMaxResults = 1;
/* The minimum distance to change Updates in meters */
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
/* The minimum time between updates in milliseconds */
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
/* Declaring a Location Manager */
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
/* getting GPS status */
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/* getting network status */
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
/* no network provider is enabled */
//gpsEnableAlertDialog();
} else {
this.canGetLocation = true;
/* First get location from Network Provider */
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
/* if GPS Enabled get LAT,LNG using GPS Services */
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* application
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/WiFi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* launch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
/* Setting Dialog Title */
//alertDialog.setTitle("GPS is settings");
/* Setting Dialog Message */
alertDialog.setMessage("GPS is disabled in your device. Enable it?");
/* On pressing Settings button */
alertDialog.setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
/* on pressing cancel button */
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
/* Showing Alert Message */
alertDialog.show();
}
/*
* Close project which is open
* this sialog is used to disable all menu item
*/
private void gpsEnableAlertDialog() {
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_close_project, null);
final NiftyDialogBuilder dialogBuilder = NiftyDialogBuilder.getInstance(mContext);
dialogBuilder.isCancelableOnTouchOutside(true).withDuration(700).withEffect(Effectstype.Shake).setCustomView(view,mContext).show();
TextView edt_searchitem_item = (TextView) view.findViewById(R.id.edt_searchitem_item);
edt_searchitem_item.setText("GPS is disabled in your device. Enable it?");
/*
* Close project and disable all menu item
*/
Button btn_closePrj_yes = (Button) view.findViewById(R.id.btn_closePrj_yes);
btn_closePrj_yes.setText("Enable GPS");
btn_closePrj_yes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialogBuilder.cancel();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
((Activity)mContext).overridePendingTransition(R.anim.right_to_left_layout,R.anim.left_to_right_layout);
}
});
/*
* return same as previouse state
*/
Button btn_close_prj_no = (Button) view.findViewById(R.id.btn_close_prj_no);
btn_close_prj_no.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialogBuilder.cancel();
}
});
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
/* Extra(Below method not use in application) */
/**
* Get list of address by latitude and longitude
*
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses that
* are known to describe the area immediately surrounding the
* given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
Toast.makeText(context, "Internet connection not available", Toast.LENGTH_SHORT).show();
Log.e("Error Msg:", "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
*
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
*
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
/**
* Try to get Postal Code
*
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
*
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
}
Download project from here (Get Current Location Using Background Service)
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#3F51B5"
android:text="Location using service"
android:textColor="#ffffff"
android:textSize="20dp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Latitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_latitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Longitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_longitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Address"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_address"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Area"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_area"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Locality"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_locality"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_start"
android:text="Get Location"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
import android.*;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.preference.PreferenceManager;
import android.renderscript.Double2;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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 java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latutide"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
GoogleService.java
package servicetutorial.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by deepshikha on 24/11/16.
*/
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;
public GoogleService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation(){
locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable){
}else {
if (isNetworkEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
if (isGPSEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask{
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}

Categories

Resources