I wanted to make sure that if the user had their GPS Location off at the start of the app a popup would appear and redirect you to the location where you could toggle the GPS Location on. I am able to do that but as soon as I go back to my app it does no longer center in my location unless i close the app and start it again. What am i doing wrong?
private boolean hasPermissions(){
return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
In the onCreate :
if (hasPermissions()) {
setMap();
initMyLocation();
centerButton();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
The setMap, initMyLocation, centerButton methods:
public void setMap(){
map = findViewById(R.id.mapview);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setTilesScaledToDpi(true);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
}
public void initMyLocation(){
final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
//Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Something.");
builder.setMessage("activate GPS.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
GpsMyLocationProvider provider = new GpsMyLocationProvider(getApplicationContext());
provider.addLocationSource(LocationManager.GPS_PROVIDER);
provider.addLocationSource(LocationManager.NETWORK_PROVIDER);
locationNewOverlay = new MyLocationNewOverlay(provider, map);
locationNewOverlay.enableMyLocation();
map.getOverlays().add(locationNewOverlay);
}
public void centerButton() {
ImageButton btCenterMap = this.findViewById(R.id.menu_mylocation);
btCenterMap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationNewOverlay.runOnFirstFix(new Runnable() {
@Override
public void run() {
myLocation = locationNewOverlay.getMyLocation();
}
});
locationNewOverlay.enableFollowLocation();
}
});
}
I think your logic needs to be something like this:
Check Method - check for permissions and whether or not GPS/Network Location is available
On resume
On Pause