RagAnt
RagAnt

Reputation: 1014

In Google Maps, why is OnLocationChanged() not called again, when the app is maximized from its minimized state?

I am developing an Android Application. In that I integrated Google Maps in a Fragment .

My Problem
In the Map , in normal running state , OnLocationChanged function called by LocationListener and my Map Marker is moving correctly.

But , if I minimizes the app and after I maximize it , the marker is not moving . I checked and found , the OnLocationChanged not get called after Maximizing the App.

So I put some Log.D commends in the onLocationChanged and reran it.

Until minimizing the App , The Log commends exectuted on each and every location changed. But After I minimized and maximized the App , The Log printing stoped and marker stopped moving.

My Efforts to Resolve
I tried implementing OnResume method in Fragment but it not called.

So I searched the internet. Based on the suggestions I recreated the Fragment on the onResume method of the parent Activity of the Fragment.

After that , the the tracking worked even after resuming. But I fell in to an another problem.

When the Fragment get Recreated in the onResume() of the parent Activity , the Map loading the from the beginning. That is the Map showing Whole world map..... then slowly it goes to current location and the old markers cleared and new markers draw again. After that marker start moving.

So that process takes long time.

Now I can't move further. Since I am new to Google Maps I can't fix it..

My Code:

Map_Fragment.java

/**
 * A simple {@link Fragment} subclass.
 */
public class Map_Fragment extends Fragment  implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, LocationSource,
        GoogleApiClient.OnConnectionFailedListener, GeoQueryEventListener, ValueEventListener,LocationListener {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private GoogleMap mMap;
    LocationManager locationManager;
    RelativeLayout toolbarLayout;
    String driverId = "5acgh565733";
    RelativeLayout progressLayout1, progresslayout, onlinelay;
    String tripState, onlinecheck;
    FrameLayout fragmentcontainer;
    TextView onlineTxt;
    SharedPreferences.Editor editor;
    String onlinestatus;
    View mapView;
    Bitmap mapBitmap;
    Marker mCurrLocationMarker;
    CameraUpdate cameraUpdate = null;
    Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;
    private OnLocationChangedListener mMapLocationListener = null;
    LocationRequest mLocationRequest;
    Dialog d, dialogTripSummary, dialog;
    ProgressWheel pwOne;
    ImageView requestMapView;
    ArrayList<LatLng> MarkerPoints;
    Location mCurrentLocation, lStart, lEnd;
    RelativeLayout FAB;
    GeoFire geoFire;
    BottomBar bottomBar;
    boolean clicked = false;


    public Map_Fragment() {
        // Required empty public constructor
    }


    @SuppressLint("CommitPrefEdits")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_map, container, false);
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        toolbarLayout = view.findViewById(R.id.toolbar);
        onlinelay = view.findViewById(R.id.onlinelay);
        onlineTxt = view.findViewById(R.id.onlineTxt);
        FAB = view.findViewById(R.id.myLocationButton);
        toolbarLayout.setVisibility(View.VISIBLE);
        bottomBar=(BottomBar)getActivity().findViewById(R.id.bottomBar);

        editor = this.getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, getActivity().MODE_PRIVATE).edit();

        if(mCurrentLocation!=null){
            LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());

            System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLng)                              // Sets the center of the map to current location
                    .zoom(15)
                    .tilt(0)                                     // Sets the tilt of the camera to 0 degrees
                    .build();

            mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.car))
                    .position(latLng));
            mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            checkOnlineStatus();
        }

        fabmethod();

        onlinelay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             //   Toast.makeText(getActivity(), "Online Clicked", Toast.LENGTH_SHORT).show();
                setOnlineStatus();

            }
        });

        return view;

    }
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if(mCurrentLocation!=null){
            LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());

            System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLng)                              // Sets the center of the map to current location
                    .zoom(15)
                    .tilt(0)                                     // Sets the tilt of the camera to 0 degrees
                    .build();

            mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.car))
                    .position(latLng));
            mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {}
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;

        Log.D(TAG,"You moved.. The current lat is "+location.getLatitude()); 
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.car));
        mCurrLocationMarker = mMap.addMarker(markerOptions);
        updateLocationToFirebase(location);

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mMapLocationListener = onLocationChangedListener;
    }
    @Override
    public void deactivate() {}

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        mMap.getMinZoomLevel();
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
            @Override
            public void onCameraMove() {
                FAB.setVisibility(View.INVISIBLE);
                toolbarLayout.setVisibility(View.INVISIBLE);
                bottomBar.setVisibility(View.GONE);
            }
        });


        mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                FAB.setVisibility(View.VISIBLE);
                bottomBar.setVisibility(View.VISIBLE);
                toolbarLayout.setVisibility(View.VISIBLE);
            }
        });

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                // mMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        } else {
            buildGoogleApiClient();
            //mMap.setMyLocationEnabled(true);
        }

        // System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation);

                if(mCurrentLocation!=null){
                    LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());

                    System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(latLng)                              // Sets the center of the map to current location
                            .zoom(15)
                            .tilt(0)                                     // Sets the tilt of the camera to 0 degrees
                            .build();
                    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                    mLocationRequest = new LocationRequest();
                    mLocationRequest.setInterval(1000);
                    mLocationRequest.setFastestInterval(1000);
                    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                    if (ContextCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
                        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, Map_Fragment.this);
                    }

                }
            }

        Toast.makeText(getActivity(),"Retriving current location. Please Wait...",Toast.LENGTH_LONG).show();

    }

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {}
    @Override
    public void onCancelled(DatabaseError databaseError) {}

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                new AlertDialog.Builder(getActivity())
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(getActivity(),
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }



        }
    }

    public void fabmethod() {
        FAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mCurrentLocation != null) {
                    LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());

                    System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(latLng)                              // Sets the center of the map to current location
                            .zoom(15)
                            .tilt(0)                                     // Sets the tilt of the camera to 0 degrees
                            .build();

                    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                }

                else{
                    Toast.makeText(getApplicationContext(),"mmap not  Added", Toast.LENGTH_SHORT).show();

                }
            }
        });
    }
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

} 

In the above Program , the onLocationChanged not called after resuming.


MainActivity.java

public class MainActivity extends FragmentActivity {

    BottomBar bottomBar;
    Fragment fragment =null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        bottomBar = (BottomBar) findViewById(R.id.bottomBar);
        bottomBar.setVisibility(View.VISIBLE);
        bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(@IdRes int tabId) {
                if (tabId == R.id.tab_profile) {
                    fragment = new Viewprofile_Fragment();
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.fragment_container, fragment);
                    transaction.commit();

                }

                if (tabId == R.id.tab_rating) {

                    fragment = new Ratings_Fragment();
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.fragment_container, fragment);
                    transaction.commit();
                }

                if (tabId == R.id.tab_earning) {

                    fragment = new Earnings_Fragment();
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.fragment_container, fragment);
                    transaction.commit();
                }
                if (tabId == R.id.tab_home) {
                  fragment = new Map_Fragment();
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.fragment_container, fragment);
                    transaction.commit();
                }
            }
        });
    }

    @Override
    public void onResume(){
        super.onResume();
        fragment = new Map_Fragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();
    }
}

In the above program, the onResume() ,method recreates the Map since the Fragment recreated. So the Map takes time to load.


Final Words
Please Help me to enable Tracking location continuously even after maximizing the App

Upvotes: 2

Views: 758

Answers (1)

ibrahim
ibrahim

Reputation: 91

 if ( mGoogleApiClient!=null  && mLocationRequest!=null )  
         LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

add this code in onResume() method of MapActivity.

Upvotes: 0

Related Questions