0

I have integrated google map in android app everything is working fine but when the app detects that the GPS of the mobile is not enabled it gives a dialog box to enable GPS and when user does so and comes back to the application the map stops reacting and becomes blue(may be focusing in ocean) and when i shake the device then the map becomes active and focuses on user current location.

I want to run this app on portrait mode so the shake option will not be very helpful.So can anybody help me with the code and tell me where am i wrong. I have tried various links and methods in onResume, onRestart but nothing was helpful.

Here is my code i am calling this setupmapifneeded function in onCreate,onResume and in onRestart but nothing is helpful.

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.

    if (mapFragment == null) {
        // Try to obtain the map from the SupportMapFragment.

        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;

                if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mMap.setMyLocationEnabled(true);


                // creating GPS Class object

                gps = new GPSTracker(MainActivity.this);

                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(), gps.getLongitude()), 15.0f));



                googleMap.addMarker(new MarkerOptions()
                        .position(new LatLng(26.89209, 75.82759))
                        .title("FUN N FOOD"));

                // check if GPS location can get
                if (gps.canGetLocation()) {
                    Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(), gps.getLongitude()), 15.0f));
                } else {


                    gpsDialog = new MaterialDialog.Builder(MainActivity.this)
                            .titleColor(getResources().getColor(R.color.grey))
                            .title("GPS Settings")
                            .content("GPS is not enabled. Do you want to go to settings menu?")
                            .positiveText("Settings")
                            .negativeText("Cancel")
                            .positiveColorRes(R.color.grey)
                            .negativeColorRes(R.color.grey)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                                    gpsDialog.dismiss();
                                }
                            })
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    gpsDialog.dismiss();
                                }
                            })
                            .show();
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(), gps.getLongitude()), 14.0f));

                }
            }
        });

    }
}

here is my activity.main

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and here is my other methods

@Override
public void onPause() {

    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();

}

@Override
public void onResume() {


    super.onResume();

    if (mAdView != null) {
        mAdView.resume();
    }

    if (mapFragment == null) {
        setUpMapIfNeeded();
    }

}

@Override
protected void onRestart() {
    super.onRestart();

    if (mapFragment == null) {
        setUpMapIfNeeded();
    }
}

@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();
}

Can anyone suggest something... Thanks in Advance

2 Answers2

0

I found a very easy way of doing this by ignoring the onResume part first of all i intergrated this in main activity (Fused location Provider Api).

and then in my splash screen i called out a method that helped me to turn on gps as the OLA app does and when the splash goes to next activity it starts focusing on user's current location without any problem.

We can do the gps thing like this: Create a function

private GoogleApiClient mGoogleApiClient;

private void automaticGps() {


    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API).addConnectionCallbacks(Splash.this)
                .addOnConnectionFailedListener(Splash.this).build();
        mGoogleApiClient.connect();
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        // **************************
        builder.setAlwaysShow(true); // this is the key ingredient
        // **************************

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
                .checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result
                        .getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can
                        // initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be
                        // fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling
                            // startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(Splash.this, 1000);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have
                        // no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        });
    }
}

override methods:

    @Override
public void onConnected(@Nullable Bundle bundle) {
    Intent i = new Intent(Splash.this,MainActivity.class);
    startActivity(i);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

and implement:

public class Splash extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

call this function in onCreate

if(!gps.canGetLocation) {
                automaticGps();
                //iv.startAnimation(an2);
            }
            else {
                //iv.startAnimation(an2);
                finish();
                Intent i = new Intent(Splash.this,MainActivity.class);
                startActivity(i);
            }

Remember:

1) use android.Manifest.permission.ACCESS_FINE_LOCATION instead of Manifest.permission.ACCESS_FINE_LOCATION

2) remove these lines from onPause() :

if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
Community
  • 1
  • 1