Google Location Services never updates - java

I have tried to figure this out for the past 48 hours, but I must be an idiot. I followed the Google documentation to try and make this weather app location aware. The problem is I don't how to make onLocationChanged() run or even know when it is supposed to run. If it doesn't run I send a request to grab data from latitude 0 and longitude 0. I have enabled all the correct permissions. Please help me...
package com.brennanglynn.brennanweather.ui;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.brennanglynn.brennanweather.R;
import com.brennanglynn.brennanweather.weather.Current;
import com.brennanglynn.brennanweather.weather.Day;
import com.brennanglynn.brennanweather.weather.Forecast;
import com.brennanglynn.brennanweather.weather.Hour;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static final String TAG = MainActivity.class.getSimpleName();
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
public static final String BG_GRADIENT = "BG_GRADIENT";
private Forecast mForecast;
private ColorWheel mColorWheel;
private int[] mBackground;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected Boolean mRequestingLocationUpdates;
protected String mLastUpdateTime;
private double mLatitude;
private double mLongitude;// = -116.2296;
#BindView(R.id.layoutBackground)
RelativeLayout mLayoutBackground;
#BindView(R.id.timeLabel)
TextView mTimeLabel;
#BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#BindView(R.id.humidityValue)
TextView mHumidityValue;
#BindView(R.id.precipValue)
TextView mPrecipValue;
#BindView(R.id.summaryLabel)
TextView mSummaryLabel;
#BindView(R.id.iconImageView)
ImageView mIconImageView;
#BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
#BindView(R.id.progressBar)
ProgressBar mProgressBar;
#BindView(R.id.locationLabel)
TextView mLocationLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
buildGoogleApiClient();
mColorWheel = new ColorWheel();
mProgressBar.setVisibility(View.INVISIBLE);
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
Log.i(TAG, "Updating values from bundle");
if (savedInstanceState != null) {
// Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
// the Start Updates and Stop Updates buttons are correctly enabled or disabled.
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
}
// Update the value of mCurrentLocation from the Bundle and update the UI to show the
// correct latitude and longitude.
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
// Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
// is not null.
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
// Update the value of mLastUpdateTime from the Bundle and update the UI.
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
updateDisplay();
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void setBackgroundGradient() {
mBackground = mColorWheel.getColors();
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[]{mBackground[0], mBackground[1]});
gd.setCornerRadius(0f);
mLayoutBackground.setBackground(gd);
}
private void getForecast(double latitude, double longitude) {
String apiKey = "50e826df5889d0d215cdcbae50d182e3";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
alertUserAboutError();
}
Log.i(TAG, forecastUrl);
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrentForecast(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Day day = new Day();
day.setTime(jsonHour.getLong("time"));
day.setSummary(jsonHour.getString("summary"));
day.setTemperatureMax(jsonHour.getInt("temperatureMax"));
day.setTimezone(timezone);
day.setIcon(jsonHour.getString("icon"));
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setTime(jsonHour.getLong("time"));
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getInt("temperature"));
hour.setTimezone(timezone);
hour.setIcon(jsonHour.getString("icon"));
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current(
currently.getString("icon"),
currently.getLong("time"),
currently.getDouble("temperature"),
currently.getDouble("humidity"),
currently.getDouble("precipProbability"),
currently.getString("summary"),
forecast.getString("timezone")
);
Log.i(TAG, current.toString());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.refreshImageView)
public void refreshPage(View view) {
mRequestingLocationUpdates = true;
getForecast(mLatitude, mLongitude);
setBackgroundGradient();
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
if (mBackground != null) {
intent.putExtra(BG_GRADIENT, mBackground);
}
startActivity(intent);
}
#OnClick(R.id.hourButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
if (mBackground != null) {
intent.putExtra(BG_GRADIENT, mBackground);
}
startActivity(intent);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void startUpdatesButtonHandler(View view) {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
startLocationUpdates();
}
}
public void stopUpdatesButtonHandler(View view) {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
stopLocationUpdates();
}
}
protected void startLocationUpdates() {
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
}
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private void updateDisplay() {
Current current = mForecast.getCurrentForecast();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("The time is " + current.getFormattedTime());
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ResourcesCompat.getDrawable(getResources(), current.getIconId(), null);
mIconImageView.setImageDrawable(drawable);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
// If the initial location was never previously requested, we use
// FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
// its value in the Bundle and check for it in onCreate(). We
// do not request it again unless the user specifically requests location updates by pressing
// the Start Updates button.
//
// Because we cache the value of the initial location in the Bundle, it means that if the
// user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
if (mCurrentLocation == null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "location changed");
mCurrentLocation = location;
mLatitude = mCurrentLocation.getLatitude();
mLongitude = mCurrentLocation.getLongitude();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
getForecast(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
updateDisplay();
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
super.onSaveInstanceState(savedInstanceState);
}
}

hi your api is working fine, i have checked. You have issue with your current latitude and longitude. So, i have one solution for you.
Please check how i'm using in my app and its working perfect.I'm using fused api for update location please follow few steps.
Step 1. Make this class
GoogleLocationService.java
public class GoogleLocationService {
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
LocationUpdateListener locationUpdateListener;
Context activity;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;
public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
this.locationUpdateListener = locationUpdateListener;
this.activity = activity;
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
//Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(activity)
.addConnectionCallbacks(callbacks)
.addOnConnectionFailedListener(callbacks)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();
}
locationUpdateListener.cannotReceiveLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location.hasAccuracy()) {
if (location.getAccuracy() < 30) {
locationUpdateListener.updateLocation(location);
}
}
}
}
private static boolean locationEnabled(Context context) {
boolean gps_enabled = false;
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
return gps_enabled;
}
private boolean servicesConnected(Context context) {
return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
}
private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
public void startUpdates() {
/*
* Connect the client. Don't re-start any requests here; instead, wait
* for onResume()
*/
if (servicesConnected(activity)) {
if (locationEnabled(activity)) {
locationUpdateListener.canReceiveLocationUpdates();
startLocationUpdates();
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
}
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
}
}
//stop location updates
public void stopUpdates() {
stopLocationUpdates();
}
//start location updates
private void startLocationUpdates() {
if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
}
}
public void stopLocationUpdates() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
}
}
public void startGoogleApi() {
mGoogleApiClient.connect();
}
public void closeGoogleApi() {
mGoogleApiClient.disconnect();
}
}
Step2. Make this interface
LocationUpdateListener.java
public interface LocationUpdateListener {
/**
* Called immediately the service starts if the service can obtain location
*/
void canReceiveLocationUpdates();
/**
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
*/
void cannotReceiveLocationUpdates();
/**
* Called whenever the location has changed (at least non-trivially)
* #param location
*/
void updateLocation(Location location);
/**
* Called when GoogleLocationServices detects that the device has moved to a new location.
* #param localityName The name of the locality (somewhere below street but above area).
*/
void updateLocationName(String localityName, Location location);
}
Step 3. Call this in your class oncreate or where you want to get location
private GoogleLocationService googleLocationService;
googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
#Override
public void canReceiveLocationUpdates() {
}
#Override
public void cannotReceiveLocationUpdates() {
}
//update location to our servers for tracking purpose
#Override
public void updateLocation(Location location) {
if (location != null ) {
Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());
}
}
#Override
public void updateLocationName(String localityName, Location location) {
googleLocationService.stopLocationUpdates();
}
});
googleLocationService.startUpdates();
and call this onDestroy
if (googleLocationService != null) {
googleLocationService.stopLocationUpdates();
}
Hope this will help you to solve your problem.

Related

Can't get GPS coordinates in android application

I use this code to get the current location's coordinates. When I start this activity, nothing happens. When I use this exact code in another application it worked. The only difference that I use this location-getter in a different class, not in MainActivity. When I open that app a service comes up and starts searching the coordinates. In this case (GetLocationPS) nothing happens.
What could be the problem?
build.gradle:
compile 'com.google.android.gms:play-services:11.0.2'
GetLocationPS.java:
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class GetLocationPS extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final String TAG = "MainActivity";
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location_ps);
mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
checkLocation(); //check whether location service is enable or not in your phone
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
Log.d("reque", "--->>>>");
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
mLongitudeTextView.setText(String.valueOf(location.getLongitude() ));
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
// You can now create a LatLng Object for use with maps
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
private boolean checkLocation() {
if(!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
}
Hope this might help
Edit:
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (!checkPermissions()) requestPermissions();
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
#Override
protected void onPause() {
super.onPause();
if(checkPermissions()) stopLocationUpdates();
}
#Override
public void onResume() {
super.onResume();
if(checkPermissions() && mGoogleApiClient.isConnected()) startLocationUpdates();
}
private void startLocationUpdates() {
//noinspection MissingPermission
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private boolean checkPermissions() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(checkPermissions() && mGoogleApiClient.isConnected()) startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
mLongitudeTextView.setText(String.valueOf(location.getLongitude()));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
} else {
}
}
}
}
}
In onLocationChanged() you get location which you can use to get latitude and longitude. Also, this code does not give continuous location updates. For that you have to set UPDATE INTERVAL & FASTEST UPDATE INTERVAL in method createLocationRequest().

Ask location permissions inside service

I am getting the location data using a service, this service is started when my app runs on a activity, and i need that activity to ask for the permissions.
So basicly this is my service (it works fine)
public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "BOOMBOOMTESTGPS";
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0f;
private int updatePriority;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private final IBinder mBinder = new LocalBinder();
private Intent intent;
private String provider;
Context context;
Location mLastLocation;
public class LocalBinder extends Binder {
public GoogleLocation getServerInstance() {
return GoogleLocation.this;
}
}
public Location getLocation() {
Log.d("IMHERE", "HELLO");
return mLastLocation;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
context = getApplicationContext();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
} else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
} else {
this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
}
this.buildGoogleApiClient();
this.createLocationRequest();
this.googleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Log.d("localizacao",mLastLocation.toString());
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
this.googleApiClient.unregisterConnectionCallbacks(this);
this.googleApiClient.unregisterConnectionFailedListener(this);
this.googleApiClient.disconnect();
this.mLastLocation = null;
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private synchronized void buildGoogleApiClient() {
this.googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void createLocationRequest() {
this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setPriority(updatePriority);
}
here is where i start it
package com.example.afcosta.inesctec.pt.android;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.afcosta.inesctec.pt.android.services.GoogleLocation;
public class LocationPermission extends AppCompatActivity {
public static final int REQ_PERMISSION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
askPermission();
Intent i = new Intent(this,Login.class);
startActivity(i);
}
// PEDIDO DE PERMISSÃO
private void askPermission() {
checkLocationPermission();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean 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("Partilhar localização")
.setMessage("Permitir a partilha de dados sobre a sua localização?")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(LocationPermission.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);
}
return false;
} else {
startService(new Intent(this, GoogleLocation.class));
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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission. ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
startService(new Intent(this, GoogleLocation.class));
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
}
the thing is, i need to ask for permissions when he runs the app for the first time, or he has the location disabled. And that never happens.
I should just start the service when the user has give the permission.
Any help with this?
Thanks
you can ask for any permission in runtime in this way:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
}
}
and you can get it's result in:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case RC_ACCESS_FINE_LOCATION: {
}
}
}
#Override
protected Boolean processInBackground(Void... params) {
PermissionResponse response = PermissionEverywhere.getPermission(getApplicationContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQ_CODE,
"Notification title",
"This app need external permisison",
R.launcher)
.call();
boolean isGranted = response.isGranted();
if(isGrante){
// here do your stuff
}
}

GPS Location always remains active in notification tray after exit MapView

Original Title:
"Location set by GPS" still remains active after
LocationServices.FusedLocationApi.removeLocationUpdates()
Edited Title:
GPS Location always remains active in notification tray after exit MapView
I want to disable remove the "Location set by GPS" and the location icon in top notification tray right after exit my map activity but it doesn't.
I'm using someone's code in stackoverflow which using following variable only:
GoogleMap mGoogleMap;
MapView mapView;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
MapLocationListener mapLocationListener;
What I've tried:
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mapLocationListener);
if(mGoogleApiClient != null){
mGoogleApiClient = null;
}
if(mapView != null){
mapView = null;
}
if(mGoogleMap != null){
mGoogleMap = null;
}
if(mLocationRequest != null){
mLocationRequest = null;
}
if(mLastLocation != null){
mLastLocation = null;
}
if(mCurrLocationMarker != null){
mCurrLocationMarker = null;
}
if(mapLocationListener != null){
mapLocationListener = null;
}
}
activity.finish();
}
I understand that assigning null to my references should not be the solution because the location process is running in system background not using my app references.And Yes, the location listener is no longer update but it just not disable the location icon on top like other apps did.
What I want:disable the "Location set by GPS" and the location icon in top notification tray immediately after exit my map activity. I don't want to make my user thinks I'm doing "location hacking"What I've found:All the solution I found is using LocationManager.removeUpdate which I don't have it. How can I declare it in my activity? Is this can really solve my problem?
EDIT: Attacthed Code:Using Daniel Nugent's answer...
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.location.LocationManager.GPS_PROVIDER;
import static android.location.LocationManager.NETWORK_PROVIDER;
/**
* Created by elliotching on 11-Apr-17.
*/
public class ActivityMaps_ extends MyCustomActivity {
GoogleMap mGoogleMap;
MapView mapView;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
MapLocationListener mapLocationListener;
LocationManager locManager;
Button buttonSaveLocation;
double[] markerLocation;
private final static int mapZoomLevel = 18;
Context context = this;
AppCompatActivity activity = (AppCompatActivity) context;
private class GoogleApiClientConnection implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnected(Bundle bundle) {
Log.d("onConnected", "onConnected.");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(50);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(context,
ACCESS_FINE_LOCATION)
== PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mapLocationListener);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
private class MapLocationListener implements com.google.android.gms.location.LocationListener {
#Override
public void onLocationChanged(Location location) {
// DO MY LOCATION UPDATE...
}
}
private class OnMapReady implements OnMapReadyCallback {
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d("onMapReady", "onMapReady.");
mGoogleMap = googleMap;
mGoogleMap.setOnMapClickListener(new OnMapTouched());
//if device OS SDK >= 23 (Marshmallow)
if (Build.VERSION.SDK_INT >= 23) {
//IF Location Permission already granted
if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED) {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
// Request Location Permission
checkLocationPermission();
}
}
//if device OS is version 5 Lollipop and below ( <= SDK_22 )
else {
if (checkLocationPermission_v22()) {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
// AlertDialog TO EXIT MAP...
}
}
}
}
private class OnMapTouched implements GoogleMap.OnMapClickListener {
#Override
public void onMapClick(LatLng latLng) {
// CHANGE MY MARKER...
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// createMyView = setContentView(...)
createMyView(R.layout.activity_maps, R.id.toolbar);
mapLocationListener = new MapLocationListener();
buttonSaveLocation = (Button) findViewById(R.id.button_save_location);
buttonSaveLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveLocation();
}
});
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReady());
mapView.onResume();
}
private void saveLocation() {
Intent i = new Intent();
i.putExtra("savedlocation", markerLocation);
setResult(RESULT_OK, i);
this.onPause();
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient != null && mapLocationListener != null) {
Log.d("FusedLocationApi", "run!");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mapLocationListener);
}
activity.finish();
}
protected synchronized void buildGoogleApiClient() {
Log.d("buildGoogleApiClient", "buildGoogleApiClient.");
GoogleApiClientConnection g = new GoogleApiClientConnection();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(g)
.addOnConnectionFailedListener(g)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkLocationPermission_v22() {
locManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
if (locManager.isProviderEnabled(GPS_PROVIDER) ||
locManager.isProviderEnabled(NETWORK_PROVIDER)) {
return true;
} else {
return false;
}
}
public static final int FR_PERMISSIONS_REQUEST_CODE_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) != PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{ACCESS_FINE_LOCATION}, FR_PERMISSIONS_REQUEST_CODE_LOCATION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case FR_PERMISSIONS_REQUEST_CODE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// AlertDialog to EXIT MAP...
}
return;
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Build.VERSION.SDK_INT > 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
this.onPause();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
this.onPause();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Use this class for location tracking .
public class FusedLocationTracker implements LocationListener, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
Context context;
protected GoogleApiClient mGoogleApiClient;
GoogleMap googleMap;
LocationRequest mLocationRequest;
Location mCurrentLocation = null;
private static final long INTERVAL = 1000 * 5;
private static final long FASTEST_INTERVAL = 1000 * 1;
String TAG = "LocationTracker";
boolean isGPSEnabled, wifiStatus;
WifiManager wifiManager;
FusedLocationDataInterface fusedLocationDataInterface;
public FusedLocationTracker(Context context){
this.context = context;
wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiStatus = wifiManager.isWifiEnabled();
if (!wifiStatus){
wifiManager.setWifiEnabled(true);
wifiManager.startScan();
}
createLocationRequest();
buildGoogleApiClient();
}
public void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Log.d(TAG, "createLocationRequest");
}
protected synchronized void buildGoogleApiClient() {
Log.d(TAG, "buildGoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "onConnected");
startLocationUpdates();
}
public void startLocationUpdates() {
Log.d(TAG, "startLocationUpdates");
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionSuspended");
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged");
if (location != null) {
fusedLocationDataInterface = (FusedLocationDataInterface) context;
fusedLocationDataInterface.getFusedLocationData(location);
}
}
public void stopLocationUpdates() {
Log.d(TAG, "stopLocationUpdates");
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
if (!wifiStatus){
wifiManager.setWifiEnabled(false);
}
}
}
}
create interface for writing location
public interface FusedLocationDataInterface {
public void getFusedLocationData(Location location);
}
In main activity in onCreate() method create object of class FusedLocationTracker.class and implement interface in the activity.
override this method
#Override
public void getFusedLocationData(Location location) {
LatLng locate = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().title("My Location").position(locate));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16.0f));
}
if you want to stop the locations service call the stopLocationUpdates().
Solved.It's my fault with not getting well known understand MapView well. Just call MapView.onPause() inside my overriden onPause() solve the problem.

Get values from Service into Activity

I wrote below code using fusedapi to get lat and longi.
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
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;
/**
* Created by DELL WORLD on 1/24/2017.
*/
public class LocationWithFusedApi extends Service implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
private LocationRequest mLocationRequest;
double lat, lon;
final static String Mydata = "MyData";
/* public LocationWithFusedApi() {
super("LocationWithFusedApi");
}*/
/*
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}*/
#Override
public void onStart(Intent intent, int startId) {
Log.d("LocationWithFusedAPI", "Called");
super.onStart(intent, startId);
mGoogleApiClient.connect();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
/* #Override
protected void onHandleIntent(Intent intent) {
}*/
#Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
System.out.println("Latest" + lat + ":" + lon);
Intent intent = new Intent();
intent.setAction("Mydata");
intent.putExtra("lat",lat);
intent.putExtra("lon",lon);
sendBroadcast(intent);
sendlat();
sendlon();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
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;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
System.out.println("Last" + lat + ":" + lon);
sendlat();
sendlon();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double sendlat() {
return lat;
}
public double sendlon() {
return lon;
}
public void removeupdate() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
Now trying to get lat and lon values in another activity to show to user via calling sendlat and sendlon but getting null. what mistake m I doing.
Here is code for activity where I m trying to get values.
public class ShareLocation extends AppCompatActivity {
GPSDataPicker gps;
String clickable = "";
Latlonreceiver latlonreceiver;
double lat, lon;
#Override
protected void onStart() {
latlonreceiver = new Latlonreceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LocationWithFusedApi.Mydata);
registerReceiver(latlonreceiver, intentFilter);
Intent intent = new Intent(ShareLocation.this, LocationWithFusedApi.class);
startService(intent);
super.onStart();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* LocationWithFusedApi locationWithFusedApi = new LocationWithFusedApi();
double latitude = locationWithFusedApi.sendlat();
double longitude = locationWithFusedApi.sendlon();*/
double latitude = lat;
double longitude = lon;
setContentView(R.layout.sharelocation);
clickable = "https://maps.google.com/?q=" + latitude + "," + longitude;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(latlonreceiver);
}
public class Latlonreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
lat = intent.getDoubleExtra("lat", 0.0);
lon = intent.getDoubleExtra("lon", 0.0);
}
}
Look into using broadcast receiver. The basic mistake here is that the retrieval of the location is running on a different thread asynchronously. So by the time you call your sendXxx() methods the location has not been resolved yet. With asynchronous code you need the service to push you the result after the location has been resolved. The standard way in this case would be the broadcast receiver.

Why the function getLastKnownLocation return Null on Android SDK?

I use android sdk on eclipse and i want to get location from device so i wrote an program in other class(diffrent from main) and i call mContext function inside this class from main class:
package com.example.deomanapp;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.example.deomanapp.MainActivity.PlaceholderFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class Mhelper {
public void mContext(Context context)
{
LocationManager lm;
lm = (LocationManager)context.getSystemService(context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String slongitude = String.valueOf((long) longitude);
String slatitude = String.valueOf((long) latitude);
Toast.makeText(context, slongitude, Toast.LENGTH_SHORT).show();
}
}
The problem is getLongitude or getLatitude return null,so the program crash on this line with this log:
04-20 04:30:30.410: E/AndroidRuntime(5151): java.lang.NullPointerException
04-20 04:30:30.410: E/AndroidRuntime(5151): at com.example.deomanapp.Mhelper.mContext(Mhelper.java:29)
What is wrong with this code ?
PS: I read other question with the same title and non of theme help (non of them have actual answer) because:
1-I test this program on the real device(not emulator) with GPS ON and working , but this program can't able to get location although the Device get its location before and it must show LastKnownLocation.
2-I gave the program ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permission.
3-I even use an function to see if the GPS is on, when i turn it off program alert me.
It was silly question to ask ,It was null because it was NULL,i understand it by comments on main question, my solution was to download android api image in sdk manager,run Google map once and send GPS location to it by DDMS and then run the program.
I have tried to modify some of my code, hopefully it works for your needs.
You will find the implementation of my LocationsCoreModule code in the bottom of the answer:
LocationsCoreModule locationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationRequest mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(5000);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(1000);
locationService = new LocationsCoreModule(this, mLocationRequest);
locationService.setLocationsListener(new LocationsCoreModuleCallback() {
#Override
public void locationClientConnected() {
Location location = locationService.getLastLocation();
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String slongitude = String.valueOf((long) longitude);
String slatitude = String.valueOf((long) latitude);
Toast.makeText(getApplicationContext(), slongitude, Toast.LENGTH_SHORT).show();
}
});
}
If you want the application to start listening for new GPS locations right away:
#Override
protected void onStart() {
super.onStart();
locationService.start(new LocationListener() {
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onStop() {
super.onStop();
locationService.stop();
}
And finally, the LocationsCoreModule:
public class LocationsCoreModule implements
GooglePlayServicesClient.ConnectionCallbacks {
private static final String TAG = "LocationsCoreModule";
public interface LocationsCoreModuleCallback {
public void locationClientConnected();
}
private LocationsCoreModuleCallback locationsCoreModuleCallback;
private com.google.android.gms.location.LocationListener locationListener;
private Location lastLocation;
private LocationClient mLocationClient;
private final LocationRequest mLocationRequest;
private final Context context;
#Inject
public LocationsCoreModule(Context context, LocationRequest locationRequest) {
this.context = context;
this.mLocationRequest = locationRequest;
}
public void setLastLocation(Location lastLocation) {
this.lastLocation = lastLocation;
}
public void setLocationsListener(
LocationsCoreModuleCallback locationsCoreModuleCallback) {
this.locationsCoreModuleCallback = locationsCoreModuleCallback;
}
public void start(
com.google.android.gms.location.LocationListener locationListener,
GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListener) {
this.locationListener = locationListener;
mLocationClient = new LocationClient(context, this,
connectionFailedListener);
mLocationClient.connect();
}
public void stop() {
if (mLocationClient != null) {
// If the client is connected
if (mLocationClient.isConnected() && locationListener != null) {
/*
* Remove location updates for a listener. The current Activity
* is the listener, so the argument is "this".
*/
mLocationClient.removeLocationUpdates(locationListener);
}
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
}
}
public boolean isConnected() {
if (mLocationClient == null) return false;
return mLocationClient.isConnected();
}
public Location getLastLocation() {
if (lastLocation != null) {
return lastLocation;
}
if (mLocationClient != null) {
if (mLocationClient.isConnected()) {
return lastLocation = mLocationClient.getLastLocation();
}
if (!mLocationClient.isConnecting())
mLocationClient.connect();
}
return null;
}
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "GooglePlayServices connected!");
Location lastLocation = mLocationClient.getLastLocation();
if (lastLocation == null)
Log.e(TAG, "Lastlocation is null even after connected!!!!");
if (locationsCoreModuleCallback != null) {
locationsCoreModuleCallback.locationClientConnected();
locationsCoreModuleCallback = null; // single shot
}
}
public void requestLocationUpdates() {
if (mLocationClient != null && mLocationClient.isConnected()) {
Log.d(TAG, "Requesting location updates");
mLocationClient.requestLocationUpdates(mLocationRequest,
locationListener);
}
}
public void stopLoactionUpdates() {
if (mLocationClient != null && mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(locationListener);
}
}
#Override
public void onDisconnected() {
Log.d(TAG, "GooglePlayServices disconnected!");
}
}

Categories

Resources