Getting location null. Disabled location then i opened my application, handled the permission, and intent to setting for location enable option. Re opened my application, it shows location null. Is there any way to get last know location if no other app have accessed the location before.
I have already defined ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION below is the code that I'm using
public class Map extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap googleMap;
private static final int Request_code=101;
Location mLocation;
private MapView mMapView;
boolean mLocationPermissionGranted=false;
private FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mFusedLocationClient= LocationServices.getFusedLocationProviderClient(this);
// initGoogleMap(savedInstanceState);
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
Log.d("bundle is not empty","true");
}else {
Log.d("bundle is empty","true");
}
mMapView = findViewById(R.id.service_center_map);
mMapView.onCreate(mapViewBundle);
//
mMapView.getMapAsync(this);
}
private void initGoogleMap(Bundle savedInstanceState){
}
public boolean isServicesOK(){
Log.d("map", "isServicesOK: checking google services version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if(available == ConnectionResult.SUCCESS){
//everything is fine and the user can make map requests
Log.d("map", "isServicesOK: Google Play Services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
//an error occured but we can resolve it
Log.d("map", "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else{
Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show();
}
return false;
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires GPS to work properly, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
Intent enableGpsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(enableGpsIntent, PERMISSION_REQUEST_ENABLE_GPS);
}
});
final AlertDialog alert = builder.create();
alert.show();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
private void getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
getLastKnowLocation();
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
private void getLastKnowLocation(){
Log.d("location","last location");
if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
return;
}
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if(task.isSuccessful()){
Location location=task.getResult();
Log.d("lat",String.valueOf(location.getLatitude()));
}else {
Log.d("Failed","");
}
}
});
}
public boolean isMapsEnabled(){
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
Log.d("gps","permission false");
return false;
}
Log.d("gps","permission true");
return true;
}
private boolean checkMapServices(){
if(isServicesOK()){
if(isMapsEnabled()){
return true;
}
}
return false;
}
@Override
protected void onResume() {
super.onResume();
if (checkMapServices()) {
if (mLocationPermissionGranted) {
getLastKnowLocation();
} else {
getLocationPermission();
}
}
}
@Override
public void onStop() {
super.onStop();
mMapView.onStop();
}
@Override
public void onStart() {
super.onStart();
mMapView.onStart();
}
@Override
public void onMapReady(GoogleMap map) {
this.googleMap=map;
googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)
!=PackageManager.PERMISSION_GRANTED){
return;
}
LatLng bhaktapur=new LatLng(27.67352,85.3877);
LatLng Imadol=new LatLng(27.66193,85.34179);
googleMap.addMarker(new MarkerOptions().position(bhaktapur).title("GarageInc, Bhaktapur"));
googleMap.addMarker(new MarkerOptions().position(Imadol).title("GarageInc, Imadol"));
googleMap.setMyLocationEnabled(true);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("map", "onActivityResult: called.");
switch (requestCode) {
case PERMISSION_REQUEST_ENABLE_GPS: {
if(mLocationPermissionGranted){
getLastKnowLocation();
}
else{
getLocationPermission();
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
}
@Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}