Use LocationManager instead of Google Play Service (completely removed).

This commit is contained in:
Dennis Guse
2019-07-11 23:15:55 +02:00
parent 44eeb9142c
commit f0eb85660a
10 changed files with 90 additions and 495 deletions
-2
View File
@@ -22,7 +22,5 @@ android {
dependencies {
implementation project(':myTracksLib')
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'androidx.appcompat:appcompat:1.0.0'
}
@@ -23,7 +23,6 @@ import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.Waypoint.WaypointType;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.GoogleLocationUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.maps.mytracks.R;
@@ -155,38 +154,6 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
};
mockContentResolver.addProvider(Settings.AUTHORITY, settingsProvider);
MockContentProvider googleSettingsProvider = new MockContentProvider(context) {
@Override
public Bundle call(String method, String arg, Bundle extras) {
return null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
return new MockCursor() {
@Override
public int getCount() {
return 1;
}
@Override
public boolean moveToNext() {
return true;
}
@Override
public String getString(int columnIndex) {
return String.valueOf(GoogleLocationUtils.USE_LOCATION_FOR_SERVICES_ON);
}
@Override
public void close() {}
};
}
};
mockContentResolver.addProvider("com.google.settings", googleSettingsProvider);
// Set the context
setContext(context);
@@ -53,7 +53,6 @@ import java.util.ArrayList;
public abstract class AbstractTrackActivity extends AbstractActivity implements ConfirmDeleteCaller {
private static final int DELETE_REQUEST_CODE = 3;
protected static final int GOOGLE_PLAY_SERVICES_REQUEST_CODE = 4;
protected static final int GPS_REQUEST_CODE = 6;
@Override
@@ -36,7 +36,6 @@ import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.apps.mytracks.util.TrackIconUtils;
import com.google.android.apps.mytracks.util.TrackRecordingServiceConnectionUtils;
import com.google.android.gms.location.LocationListener;
import com.google.android.maps.mytracks.R;
import android.app.SearchManager;
@@ -45,6 +44,7 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Looper;
import android.provider.SearchRecentSuggestions;
@@ -379,23 +379,42 @@ public class SearchListActivity extends AbstractTrackActivity implements DeleteM
final String textQuery = intent.getStringExtra(SearchManager.QUERY);
setTitle(textQuery);
final MyTracksLocationManager myTracksLocationManager = new MyTracksLocationManager(
this, Looper.myLooper(), true);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
myTracksLocationManager.close();
new Thread() {
@Override
public void run() {
SearchQuery query = new SearchQuery(
textQuery, location, -1L, System.currentTimeMillis());
doSearch(query);
}
}.start();
}
};
myTracksLocationManager.requestLastLocation(locationListener);
SearchQuery query = new SearchQuery(textQuery, null, -1L, System.currentTimeMillis());
doSearch(query);
// // TODO Why was this done? Somehow we searched by last location?
// @Deprecated
// final MyTracksLocationManager myTracksLocationManager = new MyTracksLocationManager(this, Looper.myLooper(), true);
// LocationListener locationListener = new LocationListener() {
// @Override
// public void onLocationChanged(final Location location) {
// myTracksLocationManager.close();
// new Thread() {
// @Override
// public void run() {
// SearchQuery query = new SearchQuery(
// textQuery, location, -1L, System.currentTimeMillis());
// doSearch(query);
// }
// }.start();
// }
//
// @Override
// public void onStatusChanged(String provider, int status, Bundle extras) {
// Log.w(TAG, "LocationListener.onStatusChanged(): is not implemented.");
// }
//
// @Override
// public void onProviderEnabled(String provider) {
// Log.w(TAG, "LocationListener.onProviderEnabled(): is not implemented.");
// }
//
// @Override
// public void onProviderDisabled(String provider) {
// Log.w(TAG, "LocationListener.onProviderDisabled(): is not implemented.");
// }
// };
// myTracksLocationManager.requestLastLocation(locationListener);
}
/**
@@ -197,8 +197,7 @@ public class TrackDetailActivity extends AbstractTrackActivity
@Override
public void onClick(View v) {
updateMenuItems(false, true);
TrackRecordingServiceConnectionUtils.stopRecording(
TrackDetailActivity.this, trackRecordingServiceConnection, true);
TrackRecordingServiceConnectionUtils.stopRecording(TrackDetailActivity.this, trackRecordingServiceConnection, true);
}
};
@@ -17,20 +17,19 @@
package com.google.android.apps.mytracks;
import android.Manifest;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.StrictMode;
import android.provider.Settings;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
@@ -53,7 +52,6 @@ import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.TracksColumns;
import com.google.android.apps.mytracks.fragments.ConfirmDeleteDialogFragment;
import com.google.android.apps.mytracks.fragments.FileTypeDialogFragment;
@@ -62,10 +60,8 @@ import com.google.android.apps.mytracks.io.file.TrackFileFormat;
import com.google.android.apps.mytracks.io.file.exporter.SaveActivity;
import com.google.android.apps.mytracks.io.file.importer.ImportActivity;
import com.google.android.apps.mytracks.services.ITrackRecordingService;
import com.google.android.apps.mytracks.services.MyTracksLocationManager;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.settings.SettingsActivity;
import com.google.android.apps.mytracks.util.GoogleLocationUtils;
import com.google.android.apps.mytracks.util.IntentUtils;
import com.google.android.apps.mytracks.util.ListItemUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
@@ -73,8 +69,6 @@ import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.apps.mytracks.util.TrackIconUtils;
import com.google.android.apps.mytracks.util.TrackRecordingServiceConnectionUtils;
import com.google.android.apps.mytracks.util.TrackUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.maps.mytracks.BuildConfig;
import com.google.android.maps.mytracks.R;
@@ -408,15 +402,6 @@ public class TrackListActivity extends AbstractTrackActivity implements FileType
trackRecordingServiceConnection.unbind();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GOOGLE_PLAY_SERVICES_REQUEST_CODE) {
checkGooglePlayServices();
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == GPS_REQUEST_CODE) {
@@ -470,9 +455,9 @@ public class TrackListActivity extends AbstractTrackActivity implements FileType
// TODO ?
return false;
case R.id.track_list_start_gps:
MyTracksLocationManager myTracksLocationManager = new MyTracksLocationManager(this, Looper.myLooper(), false);
if (!myTracksLocationManager.isGpsProviderEnabled()) {
intent = GoogleLocationUtils.newLocationSettingsIntent(TrackListActivity.this);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
startGps = !TrackRecordingServiceConnectionUtils.isRecordingServiceRunning(this);
@@ -502,7 +487,6 @@ public class TrackListActivity extends AbstractTrackActivity implements FileType
// Update menu after starting or stopping gps
this.invalidateOptionsMenu();
}
myTracksLocationManager.close();
return true;
case R.id.track_list_aggregated_statistics:
intent = IntentUtils.newIntent(this, AggregatedStatsActivity.class);
@@ -604,28 +588,9 @@ public class TrackListActivity extends AbstractTrackActivity implements FileType
PreferencesUtils.setString(this, R.string.stats_units_key, statsUnits);
}
checkGooglePlayServices();
requestGPSPermissions();
}
private void checkGooglePlayServices() {
int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (code != ConnectionResult.SUCCESS) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
code, this, GOOGLE_PLAY_SERVICES_REQUEST_CODE, new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
});
if (dialog != null) {
dialog.show();
}
}
}
private void requestGPSPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, GPS_REQUEST_CODE);
@@ -21,22 +21,13 @@ import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.google.android.apps.mytracks.util.GoogleLocationUtils;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
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.tasks.OnSuccessListener;
/**
* My Tracks Location Manager. Applies Google location settings before allowing
* access to {@link LocationManager}.
@@ -45,175 +36,35 @@ import com.google.android.gms.tasks.OnSuccessListener;
*/
public class MyTracksLocationManager {
/**
* Observer for Google location settings.
*
* @author Jimmy Shih
*/
private class GoogleSettingsObserver extends ContentObserver {
public GoogleSettingsObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
isAllowed = GoogleLocationUtils.isAllowed(context);
}
}
private final ConnectionCallbacks connectionCallbacks = new ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
handler.post(new Runnable() {
//Permissions should be already acquired by TrackListActivity during start up.
@SuppressLint("MissingPermission")
@Override
public void run() {
if (requestLastLocation != null) {
requestLastLocation.onLocationChanged(locationClient.getLastLocation().getResult());
requestLastLocation = null;
}
if (requestLocationUpdates != null) {
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(requestLocationUpdatesTime)
.setFastestInterval(requestLocationUpdatesTime)
.setSmallestDisplacement(requestLocationUpdatesDistance);
locationClient.requestLocationUpdates(locationRequest, requestLocationUpdates, handler.getLooper());
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
handler.post(new Runnable() {
@SuppressLint("MissingPermission")
@Override
public void run() {
if (requestLastLocation != null) {
locationClient.getLastLocation().addOnSuccessListener(
new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
requestLastLocation.onLocationChanged(location);
}
requestLastLocation = null;
}
});
}
if (requestLocationUpdates != null) {
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(requestLocationUpdatesTime)
.setFastestInterval(requestLocationUpdatesTime)
.setSmallestDisplacement(requestLocationUpdatesDistance);
locationClient.requestLocationUpdates(locationRequest, requestLocationUpdates, handler.getLooper());
}
}
});
}
};
private final Context context;
private final Handler handler;
private final FusedLocationProviderClient locationClient;
private final LocationManager locationManager;
private final ContentResolver contentResolver;
private final GoogleSettingsObserver observer;
private boolean isAllowed;
private LocationListener requestLastLocation;
private LocationCallback requestLocationUpdates;
private LocationListener requestLocationUpdates;
private float requestLocationUpdatesDistance;
private long requestLocationUpdatesTime;
public MyTracksLocationManager(Context context, Looper looper, boolean enableLocationClient) {
this.context = context;
public MyTracksLocationManager(Context context, Looper looper) {
this.handler = new Handler(looper);
if (enableLocationClient) {
locationClient = LocationServices.getFusedLocationProviderClient(context);
} else {
locationClient = null;
}
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
contentResolver = context.getContentResolver();
observer = new GoogleSettingsObserver(handler);
isAllowed = GoogleLocationUtils.isAllowed(context);
contentResolver.registerContentObserver(
GoogleLocationUtils.USE_LOCATION_FOR_SERVICES_URI, false, observer);
}
/**
* Closes the {@link MyTracksLocationManager}.
*/
public void close() {
contentResolver.unregisterContentObserver(observer);
}
/**
* Returns true if allowed to access the location manager. Returns true if
* there is no enforcement or the Google location settings allows access to
* location data.
*/
public boolean isAllowed() {
return isAllowed;
}
/**
* Returns true if gps provider is enabled.
*/
public boolean isGpsProviderEnabled() {
if (!isAllowed()) {
return false;
}
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/**
* Request last location.
*
* @param locationListener location listener
*/
public void requestLastLocation(final LocationListener locationListener) {
handler.post(new Runnable() {
@Override
public void run() {
if (!isAllowed()) {
requestLastLocation = null;
locationListener.onLocationChanged(null);
} else {
requestLastLocation = locationListener;
connectionCallbacks.onConnected(null);
}
}
});
}
/**
* Requests location updates. This is an ongoing request, thus the caller
* needs to check the status of {@link #isAllowed}.
* Requests location updates.
*
* @param minTime the minimal time
* @param minDistance the minimal distance
* @param locationListener the location listener
*/
public void requestLocationUpdates(
final long minTime, final float minDistance, final LocationCallback locationListener) {
public void requestLocationUpdates(final long minTime, final float minDistance, final LocationListener locationListener) {
handler.post(new Runnable() {
@Override
@SuppressLint("MissingPermission")
public void run() {
requestLocationUpdatesTime = minTime;
requestLocationUpdatesDistance = minDistance;
requestLocationUpdates = locationListener;
connectionCallbacks.onConnected(null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, requestLocationUpdatesTime, requestLocationUpdatesDistance, locationListener);
}
});
}
@@ -223,15 +74,8 @@ public class MyTracksLocationManager {
*
* @param locationListener the location listener
*/
public void removeLocationUpdates(final LocationCallback locationListener) {
handler.post(new Runnable() {
@Override
public void run() {
requestLocationUpdates = null;
if (locationClient != null) {
locationClient.removeLocationUpdates(locationListener);
}
}
});
public void removeLocationUpdates(final LocationListener locationListener) {
locationManager.removeUpdates(locationListener);
requestLocationUpdates = null;
}
}
@@ -27,10 +27,12 @@ import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.sqlite.SQLiteException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager.WakeLock;
@@ -70,9 +72,6 @@ import com.google.android.apps.mytracks.util.SystemUtils;
import com.google.android.apps.mytracks.util.TrackIconUtils;
import com.google.android.apps.mytracks.util.TrackNameUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationResult;
import com.google.android.maps.mytracks.R;
import java.util.concurrent.ExecutorService;
@@ -231,21 +230,38 @@ public class TrackRecordingService extends Service {
}
};
private LocationCallback locationListener = new LocationCallback() {
private LocationListener locationListener = new LocationListener() {
public void onLocationResult(final LocationResult locationResult) {
if (myTracksLocationManager == null || executorService == null
|| !myTracksLocationManager.isAllowed() || executorService.isShutdown()
|| executorService.isTerminated()) {
return;
}
executorService.submit(new Runnable() {
@Override
public void run() {
onLocationChangedAsync(locationResult.getLastLocation());
}
});
@Override
public void onLocationChanged(final Location location) {
if (myTracksLocationManager == null
|| executorService == null
|| executorService.isShutdown()
|| executorService.isTerminated()) {
return;
}
executorService.submit(new Runnable() {
@Override
public void run() {
onLocationChangedAsync(location);
}
});
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.w(TAG, "LocationListener.onStatusChanged(): is not implemented.");
}
@Override
public void onProviderEnabled(String provider) {
Log.w(TAG, "LocationListener.onProviderEnabled(): is not implemented.");
}
@Override
public void onProviderDisabled(String provider) {
Log.w(TAG, "LocationListener.onProviderDisabled(): is not implemented.");
}
};
private final Runnable registerLocationRunnable = new Runnable() {
@@ -272,7 +288,7 @@ public class TrackRecordingService extends Service {
context = this;
myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this);
handler = new Handler();
myTracksLocationManager = new MyTracksLocationManager(this, handler.getLooper(), true);
myTracksLocationManager = new MyTracksLocationManager(this, handler.getLooper());
voiceExecutor = new PeriodicTaskExecutor(this, new AnnouncementPeriodicTaskFactory());
splitExecutor = new PeriodicTaskExecutor(this, new SplitPeriodicTaskFactory());
sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
@@ -348,7 +364,6 @@ public class TrackRecordingService extends Service {
voiceExecutor = null;
}
myTracksLocationManager.close();
myTracksLocationManager = null;
myTracksProviderUtils = null;
@@ -718,7 +733,6 @@ public class TrackRecordingService extends Service {
// Update database
Track track = myTracksProviderUtils.getTrack(trackId);
if (track != null) {
// If not paused, add the last location
if (!paused) {
insertLocation(track, lastLocation, getLastValidTrackPointInCurrentSegment(trackId));
@@ -734,33 +748,6 @@ public class TrackRecordingService extends Service {
track.setName(trackName);
myTracksProviderUtils.updateTrack(track);
}
if (track.getCategory().equals(PreferencesUtils.DEFAULT_ACTIVITY_DEFAULT)) {
int activityRecognitionType = PreferencesUtils.getInt(this,
R.string.activity_recognition_type_key,
PreferencesUtils.ACTIVITY_RECOGNITION_TYPE_DEFAULT);
if (activityRecognitionType != PreferencesUtils.ACTIVITY_RECOGNITION_TYPE_DEFAULT) {
String iconValue = null;
switch (activityRecognitionType) {
case DetectedActivity.IN_VEHICLE:
iconValue = TrackIconUtils.DRIVE;
break;
case DetectedActivity.ON_BICYCLE:
iconValue = TrackIconUtils.BIKE;
break;
case DetectedActivity.ON_FOOT:
iconValue = TrackIconUtils.WALK;
break;
default:
break;
}
if (iconValue != null) {
track.setIcon(iconValue);
track.setCategory(getString(TrackIconUtils.getIconActivityType(iconValue)));
myTracksProviderUtils.updateTrack(track);
}
}
}
}
endRecording(true, trackId);
}
@@ -1041,8 +1028,7 @@ public class TrackRecordingService extends Service {
}
try {
long interval = locationListenerPolicy.getDesiredPollingInterval();
myTracksLocationManager.requestLocationUpdates(
interval, locationListenerPolicy.getMinDistance(), locationListener);
myTracksLocationManager.requestLocationUpdates(interval, locationListenerPolicy.getMinDistance(), locationListener);
currentRecordingInterval = interval;
} catch (RuntimeException e) {
Log.e(TAG, "Could not register location listener.", e);
@@ -1,178 +0,0 @@
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import com.google.android.maps.mytracks.R;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
/**
* Utilities for Google location settings
*
* @author Jimmy Shih
*/
public class GoogleLocationUtils {
private static final String TAG = GoogleLocationUtils.class.getSimpleName();
// Action to launch the google location settings
private static final String
ACTION_GOOGLE_LOCATION_SETTINGS = "com.google.android.gsf.GOOGLE_LOCATION_SETTINGS";
// Action to check if the google apps locations settings exists
private static final String
ACTION_GOOGLE_APPS_LOCATION_SETTINGS = "com.google.android.gsf.GOOGLE_APPS_LOCATION_SETTINGS";
// User has disagreed to use location for Google services
private static final int USE_LOCATION_FOR_SERVICES_OFF = 0;
// User has agreed to use location for Google services
public static final int USE_LOCATION_FOR_SERVICES_ON = 1;
/*
* The user has neither agreed nor disagreed to use location for Google
* services yet.
*/
private static final int USE_LOCATION_FOR_SERVICES_NOT_SET = 2;
private static final String GOOGLE_SETTINGS_AUTHORITY = "com.google.settings";
private static final Uri GOOGLE_SETTINGS_CONTENT_URI = Uri.parse(
"content://" + GOOGLE_SETTINGS_AUTHORITY + "/partner");
private static final String NAME = "name";
private static final String VALUE = "value";
private static final String USE_LOCATION_FOR_SERVICES = "use_location_for_services";
public static final Uri USE_LOCATION_FOR_SERVICES_URI = Uri.parse(
"content://" + GOOGLE_SETTINGS_AUTHORITY + "/partner/" + USE_LOCATION_FOR_SERVICES);
private GoogleLocationUtils() {}
/**
* Gets the gps disabled message.
*
* @param context the context
*/
public static String getGpsDisabledMessage(Context context) {
return context.getString(R.string.gps_disabled_location_mode, getLocationSettingsName(context));
}
/**
* Gets the gps disabled message when my location button is pressed.
*
* @param context the context
*/
public static String getGpsDisabledMyLocationMessage(Context context) {
return context.getString(R.string.gps_disabled_my_location_location_mode, getLocationSettingsName(context));
}
/**
* Creates a new location settings intent.
*
* @param context the context
*/
public static Intent newLocationSettingsIntent(Context context) {
Intent intent = new Intent(useGoogleLocationSettings(context) ? ACTION_GOOGLE_LOCATION_SETTINGS
: Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
/**
* Returns true if there is no enforcement or google location settings allows
* access.
*
* @param context the context
*/
public static boolean isAllowed(Context context) {
if (!isEnforceable(context)) {
return true;
}
return getUseLocationForServices(context) != USE_LOCATION_FOR_SERVICES_OFF;
}
/**
* Gets the location settings name.
*
* @param context the context
*/
private static String getLocationSettingsName(Context context) {
return context.getString(
useGoogleLocationSettings(context) ? R.string.gps_google_location_settings
: R.string.gps_location_access);
}
/**
* Returns true to use the google location settings.
*
* @param context the context
*/
private static boolean useGoogleLocationSettings(Context context) {
if (!isEnforceable(context)) {
return false;
}
return getUseLocationForServices(context) == USE_LOCATION_FOR_SERVICES_OFF;
}
/**
* Returns true if the Google location settings is enforceable.
*/
private static boolean isEnforceable(Context context) {
Intent intent = new Intent(ACTION_GOOGLE_APPS_LOCATION_SETTINGS);
ResolveInfo resolveInfo = context.getPackageManager()
.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
return resolveInfo != null;
}
/**
* Get the current value for the 'Use value for location' setting.
*
* @return One of {@link #USE_LOCATION_FOR_SERVICES_NOT_SET},
* {@link #USE_LOCATION_FOR_SERVICES_OFF} or
* {@link #USE_LOCATION_FOR_SERVICES_ON}.
*/
private static int getUseLocationForServices(Context context) {
ContentResolver contentResolver = context.getContentResolver();
String stringValue = null;
try (Cursor cursor = contentResolver.query(GOOGLE_SETTINGS_CONTENT_URI, new String[]{VALUE},
NAME + "=?", new String[]{USE_LOCATION_FOR_SERVICES}, null)) {
if (cursor != null && cursor.moveToNext()) {
stringValue = cursor.getString(0);
}
} catch (RuntimeException e) {
Log.w(TAG, "Failed to get 'Use My Location' setting", e);
}
if (stringValue == null) {
return USE_LOCATION_FOR_SERVICES_NOT_SET;
}
int value;
try {
value = Integer.parseInt(stringValue);
} catch (NumberFormatException nfe) {
value = USE_LOCATION_FOR_SERVICES_NOT_SET;
}
return value;
}
}
@@ -16,15 +16,13 @@
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.Constants;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
/**
* Utilities to access preferences stored in {@link SharedPreferences}.
@@ -32,8 +30,6 @@ import android.util.Log;
* @author Jimmy Shih
*/
public class PreferencesUtils {
public static final int ACTIVITY_RECOGNITION_TYPE_DEFAULT = DetectedActivity.UNKNOWN;
/*
* Preferences values. The defaults need to match the defaults in the xml