Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER - android

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

Related

I am getting location too late when the user turns on the location when the app is open. here's my GPSTracking code

I am new to Android, Creating a simple application based on the location.
When the user opens the app without turning on the location then it will take to the settings directly and from there if they turn on then I am
getting the lat and lang values too late.
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
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;
public class GPSTracking extends Service implements LocationListener
{
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
Location mLocation;
private double lat;
private double lng;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
private static final long MIN_TIME_BW_UPDATE = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracking(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled =
locationManager.isProviderEnabled(lo
cationManager.GPS_PROVIDER);
isNetworkEnabled =
locationManager.isProviderEnabled(locat
ionManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
//no network or gps
}
else
{
setCanGetLocation(true);
if (isNetworkEnabled)
{
if(locationManager!=null)
{
mLocation =
locationManager.getLastKnownLocation
(LocationManager.NETWORK_PROVIDER);
if(mLocation!=null)
{
setLat(mLocation.getLatitude());
setLng(mLocation.getLongitude());
}
}
}
if (isGPSEnabled)
{
if (mLocation == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
if (locationManager != null)
{
mLocation = locationManager
.getLastKnownLocation(LocationManager
.GPS_PROVIDER);
if (mLocation != null)
{
setLat(mLocation.getLatitude());
setLng(mLocation.getLongitude());
}
}
}
}
}
}
catch (Exception e)
{
//Exception
}
return mLocation;
}
public void showAlertDialog()
{
AlertDialog.Builder alertDialog = new
AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want go to
settings menu?");
alertDialog.setPositiveButton("Settings", new
DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#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)
{
//Toast.makeText(mContext, "Please turn on the location",
// Toast.LENGTH_SHORT).show();
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng; //this is the lat
}
public boolean isCanGetLocation() {
return canGetLocation;
}
public void setCanGetLocation(boolean canGetLocation)
{
this.canGetLocation = canGetLocation; //this is canGetLocation which will do the following thing.
}
}`*
You can try google api client for getting user location try this
it will turn on location without navigating in setting like other google apps
public class ActivitySignUp extends BaseActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS = 0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_activity);
setUpGClient();
}
//set user api client for access location
private synchronized void setUpGClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mylocation = location;
if (mylocation != null) {
Double latitude = mylocation.getLatitude();
Double longitude = mylocation.getLongitude();
if (latitude != 0 && longitude != 0) {
Log.e("Lat Long", "Lat " + latitude + " && Long " + longitude);
//here is your lat long
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
//Or Do whatever you want with your location
}
}
#Override
public void onConnected(Bundle bundle) {
checkPermissions();
}
#Override
public void onConnectionSuspended(int i) {
//Do whatever you need
//You can display a message here
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//You can display a message here
}
private void getMyLocation() {
if (googleApiClient != null) {
if (googleApiClient.isConnected()) {
int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, ActivitySignUp.this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied.
// You can initialize location requests here.
int permissionLocation = ContextCompat
.checkSelfPermission(ActivitySignUp.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied.
// But could be fixed by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// Ask to turn on GPS automatically
status.startResolutionForResult(ActivitySignUp.this,
REQUEST_CHECK_SETTINGS_GPS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS_GPS:
switch (resultCode) {
case Activity.RESULT_OK:
getMyLocation();
break;
case Activity.RESULT_CANCELED:
finish();
break;
}
break;
}
}
private void checkPermissions() {
int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
}
} else {
getMyLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
Let me know if it helps
As far as i know it depends on phone , wifi being on or off , accuracy
Also there are three types of location :
GPS_PROVIDER
NETWORK_PROVIDER
PASSIVE_PROVIDER
So, as per my experience I came to know that if you use :
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, new MyLocationListener());
you will get precision upto 14+ decimal places.
But if you use fusion of them like this :
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, my_google_listener);
you will get precision upto 6 to 7 decimal places. try it !!! reference
But note few things here that, GPS Provider takes time to fetch location while Google Location is much faster as it gets data from API call to its google server database.
GPS works offline while google provider gets the location via mobile or wifi data.

How I display my current location in google map? [duplicate]

This question already has answers here:
How can I show current location on a Google Map on Android Marshmallow?
(3 answers)
Closed 4 years ago.
I wants to display my location in android device in google may using marker. I have written the following code. But there has no marker in the map. I also implement the LocationListener. But no marker. I am thankful to you if you send some code or give some suggestion.
I am also checking the isProviderAvailable and provider. They are not coming properly. isProviderAvailable returns false. Is I have to change some facility on my device? or any other problem. Please share your thought. I am waiting.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private LocationManager mLocationManager = null;
private String provider = null;
private Marker mCurrentPosition = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Toast.makeText(this, "locateCurrentPosition Test", Toast.LENGTH_SHORT).show();
if (isProviderAvailable() && (provider != null)) {
locateCurrentPosition();
}
else
{
Toast.makeText(this, "Not satisfied:"+isProviderAvailable(), Toast.LENGTH_SHORT).show();
}
}
private void locateCurrentPosition() {
Toast.makeText(this, "locateCurrentPosition", Toast.LENGTH_SHORT).show();
int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist,
this);
}
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(10f).build();
if (mMap != null)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
private void addBoundaryToCurrentPosition(double lat, double lang) {
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker));
mMarkerOptions.anchor(0.5f, 0.5f);
CircleOptions mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(10000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
mMap.addCircle(mOptions);
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
}
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
}
Mainfest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.live.bbw.locationtest"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.google.android.gms:play-services-maps:11.0.4'
testCompile 'junit:junit:4.12'
}
if you need to fetch current location lat and log value and also show marker.
fetch current location lat and long value and show marker on that used below code ...
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.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) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(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,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
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.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapLocationActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! 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
}
}
}
if you want only fetch current location lat and long value and some interval time used below class i make for separate ...
public class LocationFetcher implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
// LogCat tag
private static final String TAG = LocationFetcher.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mBestReading;
private static final long ONE_MIN = 1000 * 60;
private static final long TWO_MIN = ONE_MIN * 2;
private static final long FIVE_MIN = ONE_MIN * 5;
private static final long POLLING_FREQ = 1000 * 30;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 25.0f;
private static final float MIN_LAST_READ_ACCURACY = 500.0f;
private double mLattitude;
private double mLongitue;
private double mAltitude;
private Activity mContext;
private UpdatedLocation updatedLocation;
private Location mLocation;
public void setListener(UpdatedLocation updatedLocation) {
if(mGoogleApiClient == null) {
init();
}
this.updatedLocation = updatedLocation;
updateLocation();
}
public void removeListener(){
this.updatedLocation = null;
mGoogleApiClient = null;
/*if(mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}*/
}
public LocationFetcher(Activity context) {
// First we need to check availability of play services
this.mContext = context;
// init();
// Show location button click listener
}
private void init(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
status.startResolutionForResult(mContext, 101);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
//TODO ALERT
Toast.makeText(mContext,
"context device is not supported.", Toast.LENGTH_LONG)
.show();
return false;
}
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(location != null) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
}
return;
}
}
}
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
} else {
mLocation = bestResult;
mLattitude = bestResult.getLatitude();
mLongitue = bestResult.getLongitude();
mAltitude = bestResult.getAltitude();
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
return bestResult;
}
}
return null;
}
return null;
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(android.location.Location location) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
if(updatedLocation != null)
updatedLocation.updateUI(location);
CustomLogHandler.printDebuglog("Location","========>>" + location);
}
public Location getLocation(){
return mLocation;
}
public double getLatitude(){
return mLattitude;
}
public double getLongitude(){
return mLongitue;
}
public double getAltitude(){
return mAltitude;
}
public void updateLocation(){
bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
}
public interface UpdatedLocation {
public void updateUI(Location location);
}
}
get latlng and put it in the code that i wrote bellow and put it on your OnMapReadyCallback
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if you have any other questions im there
You can retrieve onLocationChanged Listener and Add maker init
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
Implement your onLocationChanged like this
#Override
public void onLocationChanged(Location location) {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng));
marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
} else {
Toast.makeText(getContext(), "Location not found", Toast.LENGTH_SHORT).show();
}
}

My onLocationChange method is not being called

I have downloaded an android map project. And now i want to do something like this and i have implemented all of this thing but i am getting that on Location Changed method is not being called in my project but in other this method is being called. I am saying this because dialog is not being dismissed, zooming, and icon is not working,
Is there is way to solve this? or can we do all of that thing in on Map Ready which i have done in on Location change.
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
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 com.google.android.gms.location.LocationRequest;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 50;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
ProgressDialog pDialog;
#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);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
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);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
/*
Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(SearchMasjid.this, "Nearby Restaurants", Toast.LENGTH_LONG).show();*//*
}
});
Button btnHospital = (Button) findViewById(R.id.btnHospital);
btnHospital.setOnClickListener(new View.OnClickListener() {
String Hospital = "hospital";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Hospital);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(SearchMasjid.this, "Nearby Hospitals", Toast.LENGTH_LONG).show();
}
});
Button btnSchool = (Button) findViewById(R.id.btnSchool);
btnSchool.setOnClickListener(new View.OnClickListener() {
String School = "school";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
String url = getUrl(latitude, longitude, School);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(SearchMasjid.this, "Nearby Schools", 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,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new com.google.android.gms.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
});
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
//googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("location=" + "28.5930325" + "," + "77.05343359374999");
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyBYPKKBsAmKVzKpsDWpPzQFM-FgUCOdRsc");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
/*StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?placeid=qgYvCi0wMDAwMDAxNDczYmQyNDUxOjM5MGQxYWQ5MDFmOjAxNGY2ZWNiZjkyN2QzYWE&key=AIzaSyBYPKKBsAmKVzKpsDWpPzQFM-FgUCOdRsc");
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);
HomeActivity.lats=String.valueOf(latitude);
HomeActivity.lngs=String.valueOf(longitude);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
// Toast.makeText(SearchMasjid.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, new com.google.android.gms.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
});
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
hidePDialog();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.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[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.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,
android.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.
}
}
}
this is the exact answer of my question.
In that case, you have to request location updates as described at developers.google.com/android/reference/com/google/android/g‌​ms/…. You should do this in your onCreate() method. Your current location listener is from the incorrect package for your use. Use the location listener from the Google API package –
They should all be from the com.google.android.gms package. Make sure you are uniform when using the API
In order to use the onLocationChanged(Location) callback, you need to register your location listener with the location manager. Something like:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Since you have implemented the locationListener interface, for you it will look something like:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

Google Maps API not working above API 23 due to run time issues

The Problem: Maps API is working fine below API 23 but due to runtime issues, they are not getting permissions somehow on the first run. They ask for permissions the first time, but do not work for the first time. When I run the app, the second time, it works fine on API above 23 as well. But for the first run, it does not work. What this code should do, and does the second time, is ask the user to put two markers, one by one and reverse geocode it using the coordinates selected by user.
import android.Manifest;
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.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
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.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
public Button homeLocationFromPin;
public Button officeLocationFromPin;
public static double homeLatitude;
public static double officeLatitude;
public static double homeLongitude;
public static double officeLongitude;
public int count = 0;
public MarkerOptions placedHomeMarker;
public MarkerOptions placedOfficeMarker;
public static final int LOCATION_REQUEST_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermission(Manifest.permission.ACCESS_FINE_LOCATION,
LOCATION_REQUEST_CODE);
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(map);
mapFragment.getMapAsync(this);
homeLocationFromPin = (Button) findViewById(R.id.confirmHomeLocation);
homeLocationFromPin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (String.valueOf(homeLongitude) != null && String.valueOf(homeLatitude) != null) {
//Get nearby Places here based on Latitude and Longitude
// Toast.makeText(MapsActivity.this, getAddress(homeLatitude, homeLongitude), Toast.LENGTH_LONG).show();
showAlertBoxForHomeLocationConfirmation(getAddress(homeLatitude, homeLongitude));
} else {
Toast.makeText(MapsActivity.this, "Please drop pin to home location first", Toast.LENGTH_SHORT).show();
}
}
});
officeLocationFromPin = (Button) findViewById(R.id.confirmOfficeLocation);
officeLocationFromPin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (String.valueOf(officeLatitude) != null && String.valueOf(officeLongitude) != null) {
//Get nearby Places here based on Latitude and Longitude
// Toast.makeText(MapsActivity.this, getAddress(homeLatitude, homeLongitude), Toast.LENGTH_LONG).show();
showAlertBoxForOfficeLocationConfirmation(getAddress(officeLatitude, officeLongitude));
} else {
Toast.makeText(MapsActivity.this, "Please drop pin to home location first", Toast.LENGTH_SHORT).show();
}
}
});
}//End Of OnCreate
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng boston = new LatLng(42.3601, -71.0589);
mMap.moveCamera(CameraUpdateFactory.newLatLng(boston));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
showAlertBox("Home");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
Toast.makeText(this, "Inside Perm", Toast.LENGTH_LONG).show();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (count == 0) {
//Make the confirm button available on first tap
homeLocationFromPin.setVisibility(View.VISIBLE);
//add(point);
mMap.clear();
placedHomeMarker = new MarkerOptions().position(latLng);
placedHomeMarker.title("Home Location");
mMap.addMarker(placedHomeMarker);
homeLatitude = latLng.latitude;
homeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
} else {
officeLocationFromPin.setVisibility(View.VISIBLE);
placedOfficeMarker = new MarkerOptions().position(latLng);
placedOfficeMarker.title("Office Location");
mMap.addMarker(placedOfficeMarker);
officeLatitude = latLng.latitude;
officeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
Toast.makeText(MapsActivity.this, getNameOnly(officeLatitude, officeLongitude), Toast.LENGTH_SHORT).show();
}
}
});
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (count == 0) {
//Make the confirm button available on first tap
homeLocationFromPin.setVisibility(View.VISIBLE);
//add(point);
mMap.clear();
placedHomeMarker = new MarkerOptions().position(latLng);
placedHomeMarker.title("Home Location");
mMap.addMarker(placedHomeMarker);
homeLatitude = latLng.latitude;
homeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
} else {
officeLocationFromPin.setVisibility(View.VISIBLE);
placedOfficeMarker = new MarkerOptions().position(latLng);
placedOfficeMarker.title("Office Location");
mMap.addMarker(placedOfficeMarker);
officeLatitude = latLng.latitude;
officeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
Toast.makeText(MapsActivity.this, getNameOnly(officeLatitude, officeLongitude), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}//End of onMap Ready
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
// markerOptions.title("Your Current Location");
// markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.home));
// markerOptions.draggable(true);
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//Set a marker drag listener
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
mMap.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
//Get the latitude and longitude of the place where user dropped the marker
Toast.makeText(MapsActivity.this, "Latitude:" + String.valueOf(marker.getPosition().latitude), Toast.LENGTH_LONG).show();
homeLatitude = marker.getPosition().latitude;
Toast.makeText(MapsActivity.this, "Longitude:" + String.valueOf(marker.getPosition().longitude), Toast.LENGTH_LONG).show();
homeLongitude = marker.getPosition().longitude;
}
});
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void showAlertBox(String LocationName) {
AlertDialog.Builder b1 = new AlertDialog.Builder(MapsActivity.this);
b1.setMessage("Please select your " + LocationName + " location.\nTap anywhere on the screen to select your "
+ LocationName +
"location and press button to confirm.");
b1.setCancelable(false);
b1.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog customAlertBox = b1.create();
customAlertBox.show();
}
public void showAlertBoxForHomeLocationConfirmation(String reverseGeoStr) {
AlertDialog.Builder b1 = new AlertDialog.Builder(MapsActivity.this);
b1.setMessage("Confirm your home location or search again\n" + reverseGeoStr);
b1.setCancelable(false);
b1.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
count = 3;
homeLocationFromPin.setVisibility(View.GONE);
showAlertBox("Office");
}
});
b1.setNegativeButton("Do it again",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MapsActivity.this, "Place Pin Again", Toast.LENGTH_SHORT).show();
}
});
AlertDialog customAlertBox = b1.create();
customAlertBox.show();
}
public void showAlertBoxForOfficeLocationConfirmation(String reverseGeoStr) {
AlertDialog.Builder b1 = new AlertDialog.Builder(MapsActivity.this);
b1.setMessage("Confirm your Office location or search again\n" + reverseGeoStr);
b1.setCancelable(false);
b1.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent st = new Intent(MapsActivity.this, getUserName.class);
startActivity(st);
finish();
}
});
b1.setNegativeButton("Do it again",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MapsActivity.this, "Place Pin Again", Toast.LENGTH_SHORT).show();
}
});
AlertDialog customAlertBox = b1.create();
customAlertBox.show();
}
private String getAddress(double latitude, double longitude) {
if (latitude == 0.0 || longitude == 0.0) {
//Give default values so it does not returns null
latitude = 42.3601;
longitude = -71.0589;
}
StringBuilder result = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
result.append(address.getAddressLine(0)).append("\n");
result.append(address.getLocality()).append("\n");
result.append(address.getAdminArea()).append("\n");
result.append(address.getPostalCode()).append("\n");
result.append(address.getCountryName());
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return result.toString();
}
private String getNameOnly(double latitude, double longitude) {
if (latitude == 0.0 || longitude == 0.0) {
//Give default values so it does not returns null
latitude = 42.3601;
longitude = -71.0589;
}
StringBuilder result = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
result.append(address.getAddressLine(0)).append("\n");
result.append(address.getLocality()).append("\n");
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return result.toString();
}
protected void requestPermission(String permissionType, int requestCode) {
int permission = ContextCompat.checkSelfPermission(this,
permissionType);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{permissionType}, requestCode
);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_CODE: {
if (grantResults.length == 0
|| grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Unable to show location - permission required", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
As you are requesting for location update in onMapReady(), You should call mapFragment.getMapAsync(this); in onRequestPermissionsResult method:
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapFragment.getMapAsync(this);
} else {
Toast.makeText(getApplicationContext(), "Please provide the permission", Toast.LENGTH_LONG).show();
}
break;
}
}
}
Hope this helps.
The soluion above makes it work on phones with API > 23 but it stops working with API< 23. So I worked around
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_CODE: {
if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Unable to show location - permission required", Toast.LENGTH_LONG).show();
return;
}
// if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
// mapFragment.getMapAsync(this);
// }
else
{
Toast.makeText(this,"Permission not granted",Toast.LENGTH_LONG).show();
}
break;
}
}
}
}
and in onMapReady()
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng boston = new LatLng(42.3601, -71.0589);
mMap.moveCamera(CameraUpdateFactory.newLatLng(boston));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
showAlertBox("Home");
if (ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, LOCATION_REQUEST_CODE);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
buildGoogleApiClient();
Toast.makeText(this, "Inside Perm", Toast.LENGTH_LONG).show();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (count == 0) {
//Make the confirm button available on first tap
homeLocationFromPin.setVisibility(View.VISIBLE);
//add(point);
mMap.clear();
placedHomeMarker = new MarkerOptions().position(latLng);
placedHomeMarker.title("Home Location");
mMap.addMarker(placedHomeMarker);
homeLatitude = latLng.latitude;
homeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
} else {
officeLocationFromPin.setVisibility(View.VISIBLE);
placedOfficeMarker = new MarkerOptions().position(latLng);
placedOfficeMarker.title("Office Location");
mMap.addMarker(placedOfficeMarker);
officeLatitude = latLng.latitude;
officeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
Toast.makeText(MapsActivity.this, getNameOnly(officeLatitude, officeLongitude), Toast.LENGTH_SHORT).show();
}
}
});
} else {
buildGoogleApiClient();
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.
mMap.setMyLocationEnabled(true);
}
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (count == 0) {
//Make the confirm button available on first tap
homeLocationFromPin.setVisibility(View.VISIBLE);
//add(point);
mMap.clear();
placedHomeMarker = new MarkerOptions().position(latLng);
placedHomeMarker.title("Home Location");
mMap.addMarker(placedHomeMarker);
homeLatitude = latLng.latitude;
homeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
} else {
officeLocationFromPin.setVisibility(View.VISIBLE);
placedOfficeMarker = new MarkerOptions().position(latLng);
placedOfficeMarker.title("Office Location");
mMap.addMarker(placedOfficeMarker);
officeLatitude = latLng.latitude;
officeLongitude = latLng.longitude;
Toast.makeText(MapsActivity.this, getNameOnly(homeLatitude, homeLongitude), Toast.LENGTH_SHORT).show();
Toast.makeText(MapsActivity.this, getNameOnly(officeLatitude, officeLongitude), Toast.LENGTH_SHORT).show();
}
}
});
}
}//End of onMap Ready

How can I get continuous location updates in Android like in Google Maps?

I'm building a friend tracking android app. While my friend activated the app and goes away along with his GPS and cellular data on, I need to track him on my device. That's the concept.
I've implemented LocationListener class and now I can get the last updated location either from Gps or Network but is not updated unless I launch Google Maps and return to my application. After googling, I learned that location cache is updated only by GMaps.!
Is there an alternate way to continuously update location?
What if when I need to get continues location after the device locked without making use of Wakelock?
This is my location listener class:
package com.amazinginside;
/** AMAZING LOCATION SUPPORT CLASS, Devoloped By SANGEETH NANDAKUMAR */
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class AmazingLocation extends Service implements LocationListener
{
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude=0.0;
double longitude=0.0;
//MINIMUM DISTANCE FOR UPDATE (meters)
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 Meters
//MINIMUM TIME BETWEEN UPDATES
private static final long MIN_TIME_BW_UPDATES = 1000 * 0; // 0 Seconds
//LOCATION MANAGER
protected LocationManager locationManager;
//CONSTRUCTOR
public AmazingLocation(Context context)
{
this.mContext = context;
getLocation();
}
//LOCATION PROVISION
public Location getLocation()
{
try
{
//GET LOCATION MANAGER
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//CHECK GPS STATE
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//CHECK NETWORK STATE
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
//NO LOCATION PROVIDERS
}
else
{
this.canGetLocation = true;
/** GET LOCATION FROM NETWORK */
//FIRST GET LOCATION FROM NETWORK
if (isNetworkEnabled)
{
//REQUEST LOCATION
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null)
{
//START WITH LAST KNOWN LOCATION
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//EXTRACT LOCATION
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
/** GET LOCATION FROM GPS SENSOR */
//THEN GET LOCATION FROM GPS
if (isGPSEnabled)
{
if (location == null)
{
//REQUEST GPS LOCATION
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null)
{
//EXTRACT LAST KNOWN LOCATION
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//RETURN LOCATION
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
//STOP GPS SENSOR
public void stopUsingGPS()
{
if(locationManager != null)
{
locationManager.removeUpdates(AmazingLocation.this);
}
}
//EXTRACT LATTITUDE
public double getLatitude()
{
if(location != null)
{
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
//EXTACT LONGITUDE
public double getLongitude()
{
if(location != null)
{
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
//CAN I GET THE LOCATION.?
public AmazingStatus canGetLocation()
{
AmazingStatus status=new AmazingStatus();
if(this.canGetLocation)
{
status.setStatus(true);
status.setErrorcode(0);
status.setErrormsg("Task completed");
}
else
{
status.setStatus(false);
status.setErrorcode(145);
status.setErrormsg("Please turn on GPS access manually");
}
return status;
}
//SHOW LOCATION SETTINGS
public AmazingStatus showSettingsAlert()
{
final AmazingStatus status=new AmazingStatus();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("REQUIRES LOCATION ACCESS");
alertDialog.setMessage("Please allow GPS access to this app");
//POSSITIVE REPLY
alertDialog.setPositiveButton("Allow", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
status.setStatus(true);
status.setErrorcode(0);
status.setErrormsg("Task completed");
}
});
//NEGATIVE REPLY
alertDialog.setNegativeButton("Deny", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
status.setStatus(false);
status.setErrorcode(408);
status.setErrormsg("User denied permission");
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
return status;
}
//UNUSED OVERRIDE METHORDS...
#Override
public void onLocationChanged(Location location)
{
getLocation();
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
getLocation();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
getLocation();
}
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
}
This my onCreate() method:
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//CREATE A BUTTON HANDLER
Button start_btn=(Button)findViewById(R.id.start_location_streaming);
//ON BUTTON CLICK EVENT
start_btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//REPEAT A METHORD AT SPECIFIC INTERVALS
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 0, 8000);
}
}); }
These are other methods:
private void TimerMethod()
{
//START METHORD
this.runOnUiThread(Timer_Tick);
}
//LOCATION REPORTING METHORD
private Runnable Timer_Tick = new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this, "Current latitude : "+Double.toString(getLocation().latitude), Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Current longitude : "+Double.toString(getLocation().longitude), Toast.LENGTH_SHORT).show();
}
};
private LatLng getLocation()
{
//CREATE A LOCATION CLASS INSTANCE
AmazingLocation gps = new AmazingLocation(this);
//RETRIVE LOCATION
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
//RETURN LOCATION
LatLng loc=new LatLng(latitude,longitude);
return loc;
}
Now the problem is, the toast just shows previously known the location and not updating unless I opened Google Maps and returned.
Any help will be great for me.
Use Fused location provider in Android set your interval in that:
For an example create your activity like this:
public class LocationActivity extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
Google play services required:
To get continiuos location update, you can refer to the above provided answers .
But You can also make use of LocationServices which is faster than other approaches and much easy and efficient to get location.
This approach is quit long but kindly follow all the provided steps
So let me provide a brief working :
Add these two dependencies in your gradle app file
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
Add these permissions in the manifest file outside applicationtag
Declare variable outside onCreate
private FusedLocationProviderClient fusedLocationClient;
private LocationRequest mLocationRequest;
private LocationCallback mlocationCallback;
private LocationSettingsRequest.Builder builder;
private static final int REQUEST_CHECK_SETTINGS = 102;
Now inside onCreate :
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
mlocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
Log.e("CONTINIOUSLOC: ", location.toString());
}
};
};
mLocationRequest = createLocationRequest();
builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
checkLocationSetting(builder);
No define fetchLastLocation method
private void fetchLastLocation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
// Toast.makeText(MainActivity.this, "Permission not granted, Kindly allow permission", Toast.LENGTH_LONG).show();
showPermissionAlert();
return;
}
}
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
Log.e("LAST LOCATION: ", location.toString()); // You will get your last location here
}
}
});
}
Now define other two method for permission request
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 123: {
// If request is cancelled, the result arrays are empty.
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// permission was denied, show alert to explain permission
showPermissionAlert();
}else{
//permission is granted now start a background service
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
}
}
}
}
}
private void showPermissionAlert(){
if (ActivityCompat.checkSelfPermission(MainHomeActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainHomeActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainHomeActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
}
}
now define createLocationRequest method and checkLocationSetting method :
protected LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(30000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setSmallestDisplacement(30);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
private void checkLocationSetting(LocationSettingsRequest.Builder builder) {
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
startLocationUpdates();
return;
}
});
task.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull final Exception e) {
if (e instanceof ResolvableApiException) {
// Location settings are not satisfied, but this can be fixed
AlertDialog.Builder builder1 = new AlertDialog.Builder(mContext);
builder1.setTitle("Continious Location Request");
builder1.setMessage("This request is essential to get location update continiously");
builder1.create();
builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(MainHomeActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e1) {
e1.printStackTrace();
}
}
});
builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "Location update permission not granted", Toast.LENGTH_LONG).show();
}
});
builder1.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_OK) {
// All location settings are satisfied. The client can initialize
// location requests here.
startLocationUpdates();
}
else {
checkLocationSetting(builder);
}
}
}
now atlast define startLocationUpdates and stopLocationUpdates method :
public void startLocationUpdates() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
}
fusedLocationClient.requestLocationUpdates(mLocationRequest,
mlocationCallback,
null /* Looper */);
}
private void stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(mlocationCallback);
}
Note : Replace context with your class context and call stopLocationUpdates() inside onDestroy method of your class
Note : For any futher information or doubt you can refer to :
https://developer.android.com/training/location/retrieve-current
https://developer.android.com/training/location/change-location-settings
https://developer.android.com/training/location/receive-location-updates
You will get your location in Logcat.
Hope this will hope you or somebody else !
I believe rather than reinventing the wheel, you can use one of the third party libraries that are easy to implement and in this case, battery efficient. One of the library I found is SmartLocation. You can add the following dependency in your build.gradle (app) to start using the library.
compile 'io.nlopez.smartlocation:library:3.2.9'
After adding the dependency, you should rebuild the project to get the references.
As an example you can try the following code in your Activity.
Button start_btn=(Button)findViewById(R.id.start_location_streaming);
Context context = start_btn.getContext();
Handler handler = new Handler();
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SmartLocation.with(context).location().start(locationListener);
}
});
OnLocationUpdatedListener locationListener = new OnLocationUpdatedListener({
#Override
public void onLocationUpdated(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
handler.postDelayed(locationRunnable,8000);
}
});
Runnable locationRunnable = new Runnable({
#Override
public void run() {
SmartLocation.with(context).location().start(locationListener);
}
});
You can stop location tracking in onStop() method
#Override
public void onStop() {
SmartLocation.with(context).location().stop();
super.onStop();
}
SmartLocation library will give you more than what is expected, just try that once.
Note: Make sure your application does have ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION (both) to have accurate results. Don't forget to ask for permissions at runtime for Android 6.0 and above.
You should use android services, rather than the app itself. This way you will achieve to run code continuously in the background and you will receive the location even if the app closes.
https://www.tutorialspoint.com/android/android_services.htm

Categories

Resources