Skip to content Skip to sidebar Skip to footer

Get User's Current Location Using Gps

I'm new in android. I'm currently working on an android project in witch I need to get user's current location using GPS. But my code is not working properly. java Code package com

Solution 1:

Use this class for getting Current Location in your App this is perfectly works for me

/**
 *         Gps location tracker class
 *         to get users location and other information related to location
 */publicclassGpsLocationTrackerextendsServiceimplementsLocationListener
{

    /**
     * context of calling class
     */private Context mContext;

    /**
     * flag for gps status
     */private boolean isGpsEnabled = false;

    /**
     * flag for network status
     */private boolean isNetworkEnabled = false;

    /**
     * flag for gps
     */private boolean canGetLocation = false;

    /**
     * location
     */private Location mLocation;

    /**
     * latitude
     */privatedouble mLatitude;

    /**
     * longitude
     */privatedouble mLongitude;

    /**
     * min distance change to get location update
     */privatestatic final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;

    /**
     * min time for location update
     * 60000 = 1min
     */privatestatic final long MIN_TIME_FOR_UPDATE = 60000;

    /**
     * location manager
     */private LocationManager mLocationManager;


    /**
     * @param mContext constructor of the class
     */publicGpsLocationTracker(Context mContext) {

        this.mContext = mContext;
        getLocation();
    }


    /**
     * @return location
     */public Location getLocation() {

        try {

            mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            /*getting status of the gps*/
            isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            /*getting status of network provider*/
            isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGpsEnabled && !isNetworkEnabled) {

                /*no location provider enabled*/
            } else {

                this.canGetLocation = true;

                /*getting location from network provider*/if (isNetworkEnabled) {

                    mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);

                    if (mLocationManager != null) {

                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                        if (mLocation != null) {

                            mLatitude = mLocation.getLatitude();

                            mLongitude = mLocation.getLongitude();
                        }
                    }
                    /*if gps is enabled then get location using gps*/if (isGpsEnabled) {

                        if (mLocation == null) {

                            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);

                            if (mLocationManager != null) {

                                mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                                if (mLocation != null) {

                                    mLatitude = mLocation.getLatitude();

                                    mLongitude = mLocation.getLongitude();
                                }

                            }
                        }

                    }
                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return mLocation;
    }

    /**
     * call this function to stop using gps in your application
     */publicvoidstopUsingGps() {

        if (mLocationManager != null) {

            mLocationManager.removeUpdates(GpsLocationTracker.this);

        }
    }

    /**
     * @return latitude
     *         <p/>
     *         function to get latitude
     */publicdoublegetLatitude() {

        if (mLocation != null) {

            mLatitude = mLocation.getLatitude();
        }
        return mLatitude;
    }

    /**
     * @return longitude
     *         function to get longitude
     */publicdoublegetLongitude() {

        if (mLocation != null) {

            mLongitude = mLocation.getLongitude();

        }

        return mLongitude;
    }

    /**
     * @return to check gps or wifi is enabled or not
     */public boolean canGetLocation() {

        returnthis.canGetLocation;
    }

    /**
     * function to prompt user to open
     * settings to enable gps
     */publicvoidshowSettingsAlert() {

        AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(new ContextThemeWrapper(mContext, R.style.AppTheme));

        mAlertDialog.setTitle("Gps Disabled");

        mAlertDialog.setMessage("gps is not enabled . do you want to enable ?");

        mAlertDialog.setPositiveButton("settings", new OnClickListener() {

            publicvoidonClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent mIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(mIntent);
            }
        });

        mAlertDialog.setNegativeButton("cancle", new OnClickListener() {

            publicvoidonClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.cancel();

            }
        });

        final AlertDialog mcreateDialog = mAlertDialog.create();
        mcreateDialog.show();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stubreturnnull;
    }

    publicvoidonLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    publicvoidonProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    publicvoidonProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    publicvoidonStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

}

& Use it this way

GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(YourActivity.this);

    /**
         * Set GPS Location fetched address
         */if (mGpsLocationTracker.canGetLocation()) 
        {
            latitude = mGpsLocationTracker.getLatitude();
            longitude = mGpsLocationTracker.getLongitude();
            Log.i(TAG, String.format("latitude: %s", latitude));
            Log.i(TAG, String.format("longitude: %s", longitude));

        } 
        else 
        {
            mGpsLocationTracker.showSettingsAlert();
        }

& don't forget to set permission in Manifest.xml

<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>

Solution 2:

LocationManagermanager= (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); 
Locationloc=   manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

Toast.makeText( getApplicationContext(),"My current location is: " + "Latitud =" +
  loc.getLatitude() + "Longitud = " + loc.getLongitude(),Toast.LENGTH_SHORT).show();

Solution 3:

Try this,

LocationManagerlocationManager= (LocationManager) getSystemService(LOCATION_SERVICE);
                Criteriacriteria=newCriteria();
                Stringprovider= locationManager.getBestProvider(criteria,
                        true);
                Locationlocation= locationManager
                        .getLastKnownLocation(provider);
                if (location != null) {
                    onLocationChanged(location);
                }
                // updates location 30seconds once
                locationManager
                        .requestLocationUpdates(provider, 30000, 0, this);

Solution 4:

Use commonsware library instead..it is much stable than other codes ...you just have to download the library from here

https://github.com/commonsguy/downloads/blob/master/CWAC-LocationPoller.jar

and here is the code

publicclassLocationReceiverextendsBroadcastReceiver {
    @OverridepublicvoidonReceive(Context context, Intent intent) {

  Log.i(getClass().getSimpleName(), "Received intent for " +   intent.getComponent().flattenToShortString());

        try {      
            Bundle b=intent.getExtras();

            LocationPollerResultlocationResult=newLocationPollerResult(b);

            Location loc=locationResult.getLocation();
            String msg;

            if (loc==null) {
                loc=locationResult.getLastKnownLocation();

                if (loc==null) {
                    msg=locationResult.getError();
                }
                else {
                    msg="TIMEOUT, lastKnown="+loc.toString();
                }
            }
            else {
                msg=loc.toString();
            }

            if (msg==null) {
                msg="Invalid broadcast received!";      
            }

            Log.i(getClass().getSimpleName(), "received location: " + msg);   

        }
        catch (Exception e) {
            Log.e(getClass().getName(), e.getMessage());
        }
    }

Solution 5:

These are the two methods how you can get user's location

  • If you use NETWORK_PROVIDER, it works both indoor and outdoor but the acuuracy is quite less.
  • If you use GPS_PROVIDER, it works outdoor only and the accuracy is good.

    String locationProvider = LocationManager.NETWORK_PROVIDER;

    String locationProvider = LocationManager.GPS_PROVIDER;

Along with the required permissions in the Manifest

Post a Comment for "Get User's Current Location Using Gps"