Skip to content

Instantly share code, notes, and snippets.

@Logicbloke
Created January 13, 2018 09:59
Show Gist options
  • Save Logicbloke/9793179b670f1fcb6e6ed6dc3907712a to your computer and use it in GitHub Desktop.
Save Logicbloke/9793179b670f1fcb6e6ed6dc3907712a to your computer and use it in GitHub Desktop.
Geolocation across Android versions
public class MainActivity extends AppCompatActivity {
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
private LocationManager locationManager;
private LocationListener locationListener;
private Location CurrentLocation;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
prefs = getPreferences(Context.MODE_PRIVATE);
double SavedLocationLat = Double.parseDouble(prefs.getString("SAVED_LOC_LAT", "0" ));
double SavedLocationLng = Double.parseDouble(prefs.getString("SAVED_LOC_LNG", "0" ));
long SavedLocationOld = Long.parseLong(prefs.getString("SAVED_LOC_OLD", "0" ));
if(SavedLocationLat + SavedLocationLng + SavedLocationOld > 0) {
Location SavedLocation = new Location(LocationManager.PASSIVE_PROVIDER);
SavedLocation.setLatitude(SavedLocationLat);
SavedLocation.setLongitude(SavedLocationLng);
SavedLocation.setTime(SavedLocationOld);
CurrentLocation = SavedLocation;
// Update if stored location is older than 40 minutes
//Log.d("TIME", "S:"+ System.currentTimeMillis()+", OLD:"+SavedLocationOld);
if(System.currentTimeMillis() - SavedLocationOld >= 40*60*1000)
RequestLocationUpdates();
}
if (CurrentLocation == null) {
if (Build.VERSION.SDK_INT >= 23) {
helloMarshMallow();
} else {
RequestLocationUpdates();
}
} else {
loadSite(CurrentLocation);
}
} catch (SecurityException se) {
Toast.makeText(MainActivity.this, "Permissions Error.", Toast.LENGTH_LONG)
.show();
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if(CurrentLocation != null) {
savedInstanceState.putDouble("SAVED_LOCATION_LAT", CurrentLocation.getLatitude());
savedInstanceState.putDouble("SAVED_LOCATION_LNG", CurrentLocation.getLongitude());
super.onSaveInstanceState(savedInstanceState);
}
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
double SavedLocLat = savedInstanceState.getDouble("SAVED_LOCATION_LAT");
double SavedLocLng = savedInstanceState.getDouble("SAVED_LOCATION_LNG");
Location SavedLoc = new Location(LocationManager.PASSIVE_PROVIDER);
SavedLoc.setLatitude(SavedLocLat);
SavedLoc.setLongitude(SavedLocLng);
CurrentLocation = SavedLoc;
loadSite(CurrentLocation);
}
private void RequestLocationUpdates() throws SecurityException {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) &&
CurrentLocation == null) {
Toast.makeText(MainActivity.this, "Please enable location services.", Toast.LENGTH_LONG)
.show();
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);
} else {
Toast.makeText(MainActivity.this, "Determining current location, please wait...", Toast.LENGTH_LONG)
.show();
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
webView.getSettings().setGeolocationEnabled(false);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SAVED_LOC_LAT", location.getLatitude() + "");
editor.putString("SAVED_LOC_LNG", location.getLongitude() + "");
editor.putString("SAVED_LOC_OLD", location.getTime() + "");
editor.commit();
loadSite(location);
locationManager.removeUpdates(locationListener);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
RequestLocationUpdates();
}
private void loadSite(Location location) throws SecurityException {
Location locGPS = null, locGSM = null;
if(locationManager != null) {
locGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locGSM = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
Location loc = location;
if(locGPS != null && locGSM != null) {
if(locGPS.getElapsedRealtimeNanos() <= locGSM.getElapsedRealtimeNanos())
loc = locGPS;
else
loc = locGSM;
} else if(locGPS != null) {
loc = locGPS;
} else if(locGSM != null) {
loc = locGSM;
}
if(loc != null) {
CurrentLocation = loc;
// Do something with loc.getLatitude() & loc.getLongitude()
}
}
/**
* WebChromeClient subclass handles UI-related calls
* Note: think chrome as in decoration, not the Chrome browser
*/
public class GeoWebChromeClient extends android.webkit.WebChromeClient {
@Override
public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
// Always grant permission since the app itself requires location
// permission and the user has therefore already granted it
callback.invoke(origin, true, false);
}
}
/**
* Check if there is any connectivity
*
* @return is Device Connected
*/
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != cm) {
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "All Permissions granted, thank you.", Toast.LENGTH_SHORT)
.show();
RequestLocationUpdates();
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "One or More Permissions were denied, closing app.", Toast.LENGTH_SHORT)
.show();
finish();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@TargetApi(Build.VERSION_CODES.M)
private void helloMarshMallow() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("Show Location");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
} else {
RequestLocationUpdates();
}
return;
}
}
@TargetApi(Build.VERSION_CODES.M)
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment