logo
down
shadow

Android Location Update not returning


Android Location Update not returning

Content Index :

Android Location Update not returning
Tag : android , By : scott.sizemore
Date : December 05 2020, 12:22 PM

will be helpful for those in need I am trying to get android location , I have this piece of code yet location is never returned. I have searched on stack overflow. , Use this class: (To use it:
FindGPSLocation gps;
                    gps = new FindGPSLocation(ClientsActivity.this);
                    if(gps.canGetLocation()){

                        latitude = String.valueOf(gps.getLatitude());
                        longitude = String.valueOf(gps.getLongitude());

                    }
                    else
                    {

                        gps.showSettingsAlert();
                    }
public class FindGPSLocation extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public FindGPSLocation(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(FindGPSLocation.this);
    }
}

/**
 * Function to get latitude
 */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 *
 * @return boolean
 */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Android : Location Update in Mapview takes to long even tough Location is found


Tag : android , By : user179190
Date : March 29 2020, 07:55 AM
wish of those help MyLocationOverlay is a helper class of Google Maps for Android. It does it's own location acquiring, more specifically it uses GPS to do it.
Since you call runOnFirstFix(runnable) it waits to get a GPS fix before executing your code. This can sometimes (especially indoor) take minutes. Hence the delay. It's also entirely possible to acquire network-based location, but not GPS position (especially indoors), so in this case your code would never be executed (except if MyLocationOverlay falls back to network provider after timeout - this isn't explained anywhere).

Android Location not returning Location from Custom Class


Tag : java , By : n1ckless_id
Date : March 29 2020, 07:55 AM
I hope this helps you . I'm not sure what is your problem but this is my code which is under load and fully functional.
Since this class extends from Fragment then it can act as parent of your fragment. There is a listener that your class can get new location after each interval.
public class LocationFinderFragment extends Fragment implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    public interface OnNewLocationFoundListener {
        public void OnNewLocationFound(Location location);
    }

    private static final String TAG = "LocationFinderFragment";
    private static final long DEFAULT_UPDATE_LOCATION_INTERVAL = 30 * 1000; // update every 30 seconds
    private static final long DEFAULT_TERMINATE_SAT_FINDING = 1 * 60 * 60 * 1000; // for 1 hour

    private OnNewLocationFoundListener listener;  // Listener of fragments
    private OnNewLocationFoundListener listener2; // Listener of MainFragmentHolder
    private Context context;
    private LocationClient mLocationClient;
    private static double lat = 0;
    private static double lng = 0;
    private static long lastTime = 0;

    private LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if(location == null)
                return;

            if(lat == location.getLatitude()  &&  lng == location.getLongitude()) {
                Log.e(TAG, "location not changed.");
                return;
            }

            lat = location.getLatitude();
            lng = location.getLongitude();
            Log.i(TAG, "Location changed to (" + lat + ", " + lng + ")");

            // Ask fragment to get new data and update screen
            listener.OnNewLocationFound(location);

            // Display toast notification every minute (instead of every 30 seconds)
            DateTime time = new DateTime();
            long currentTime = time.getMillis();
            if(currentTime > lastTime + 1 * 60 * 1000) {
                listener2.OnNewLocationFound(location);
                lastTime = currentTime;
            }
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            listener2 = (OnNewLocationFoundListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnNewLocationFoundListener interface.");
        }

        Log.i(TAG, "Fragment attached to activity.");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Getting context
        context = getActivity().getApplicationContext();

        // Get location manager
        mLocationClient = new LocationClient(context, this, this);
    }

    @Override
    public void onResume() {
        super.onResume();

        // Get location
        if(mLocationClient != null)
            mLocationClient.connect();
    }

    @Override
    public void onPause() {
        super.onPause();

        // remove listener in order to save resource
        if(mLocationClient != null)
            mLocationClient.disconnect();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // remove listener in order to save resource
        if(mLocationClient != null)
            mLocationClient.disconnect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG, "Location Connected.");
        // Get last known location
        Location lastLocation = mLocationClient.getLastLocation();
        mLocationListener.onLocationChanged(lastLocation);

        if(!SpGodMode.isLocationModeEnabled(context)) {
            // Create location request
            LocationRequest locationRequest = LocationRequest.create()
                    .setInterval(DEFAULT_UPDATE_LOCATION_INTERVAL)
                    .setExpirationDuration(DEFAULT_TERMINATE_SAT_FINDING)
                    .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            mLocationClient.requestLocationUpdates(locationRequest, mLocationListener);
        } else {
            String strLoc = SpGodMode.getLocation(context);
            if(strLoc != null) {
                String lat = strLoc.substring(0, strLoc.indexOf(","));
                String lng = strLoc.substring(strLoc.indexOf(",") + 1);
                Location location = new Location("");
                try {
                    location.setLatitude(Double.parseDouble(lat));
                    location.setLongitude(Double.parseDouble(lng));
                    mLocationListener.onLocationChanged(location);
                } catch (NumberFormatException e) {
                    Log.e(TAG, "Wrong lat/lng for parsing as Double.");
                    Toast.makeText(context, "Wrong lat/lng", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onDisconnected() {
        Log.i(TAG, "Location Disconnected.");
        if(mLocationClient != null  &&  mLocationClient.isConnected())
            mLocationClient.removeLocationUpdates(mLocationListener);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(TAG, "Connection failed listener.");
    }

    public void setLocationListener(OnNewLocationFoundListener listener) {
        this.listener = listener;
    }

    public void disconnectLocation() {
        mLocationClient.disconnect();
    }
}

using Location Services fusedlocationapi in Android service -- Receiving only one location update


Tag : android , By : ikey
Date : March 29 2020, 07:55 AM
help you fix your problem I'm trying my hand at making a background service that I'd like to run when the app is closed and terminate when the app is open.
if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

Android Location.distanceTo(...) and Location.bearingTo(...) not returning correct results


Tag : android , By : Hugo Hernan Buitrago
Date : March 29 2020, 07:55 AM

Import com.google.android.gms.location.LocationServices, can't update location services


Tag : android , By : n800s
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Retrieve a list of images from the Database and display them using a ListView?
  • java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
  • Timer/hourglass wont stop
  • How can I make AndroidX the default library for new Android projects?
  • Is it okay to delete buildToolsVersion android studio because of a warning in the Asyncstorage library?
  • Can I call a class that doesn't have an activity withIntent?
  • Android TextView fontFamily not working when set via TextAppearance
  • Unable to find nearby places
  • Is there any way to launch my application right away without 'Ok Google"?
  • Places api set location biased based on current location
  • Layout Preview is not displaying layout when Material Design is added
  • How do I resolve this diamond problem in Kotlin?
  • How to update the custom value in a view model object
  • How to stop refreshing/re-creating activity when updating Firebase data using setValue?
  • Manifest Permissions vs App Setttings Permissions
  • NumberFormatException in Try-Catch while converting String to Int
  • How to pass observable fields through include tag?
  • Next button on Android keyboard not submitting form
  • Does Firestore support automatic functions for updates?
  • Why app crashing because of a missing dimension (for google maps) only when I apply changes?
  • How to make a grouping, ordering and sorting: Kotlin collection
  • how to use augmented reality to change the color of a qr code once it is detected using with arcore and ml kit firebase
  • how to resolve Firebase projects adding quota problem?
  • Why it Kotlin giving me the wrong Int value when converting from a String
  • How to add bottom navigation listeners to fragments
  • Why is scrollview hiding buttons behind other views?
  • Open Settings using Linking.sendIntent()
  • How do I access an unknown node in firebase while retrieving data?
  • Can't retrieve list of all users from firebase authetication
  • many activities with same content (adview, reward adview, functions...) how to avoid repeating code?
  • Popup doesn't hide when touch outside
  • proper way to handling images in Android? by using Firebase
  • Android: Button is faded gray when it should be transparent
  • Gradle DSL method not found: 'deleteAllActions()'
  • In Clean Architecture, must Repository is Android or Kotlin module?
  • Kotlin parse double from string
  • Inconsistency detected. Invalid view holder adapter positionViewHolder
  • In App Update API always returns 1 (UPDATE_NOT_AVAILABLE)
  • Event of ImageView when click
  • Basic precautions to prevent piracy?
  • What is the difference between 'center' and 'centerCrop' in the "ImageView"?
  • Unable to receive SIP calls when app is killed
  • Android emulator not processing http get request, but iOS simulator works fine
  • Android Problem with sharing temporary file
  • How to add Broadcast in Android?
  • How to hide 'Running in Chrome' toast on TWA application on Android devices?
  • How to Fix Error: Could not find method deleteAllActions() for arguments [] on task
  • Android Deep Linking not working with https
  • WARNING: API 'variant.getMergeResources()' is obsolete and has been replaced with 'variant.getMergeResourcesProvider()'
  • setSupportActionBar (androidx.appcompat.widget.Toolbar) in AppCompatActivity¬†cannot be applied
  • Manifest merger failed after adding Firebase core version 17.0.0
  • Marker from Firestore map data type
  • Cordova signed apk produces a blank screen after splash screen
  • How to clear EditText input from all item views of RecyclerView?
  • Android Studio Mac Fresh install - error after error after error
  • Android Q, programmatically connect to different WiFi AP for internet
  • Application is becoming very slow while retrieving data from server
  • How to get Accelerometer value in Android XAML App(Xamarin.Forms)
  • androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.TextView
  • Synchronized singleton in Kotlin
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com