2

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.example.checkinapp;

    import android.app.Activity;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.TextView;

    public class MainActivity extends Activity 
    {

        TextView textlat;
        TextView textlong;

        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textlat = (TextView)findViewById(R.id.textlat);
            textlong = (TextView)findViewById(R.id.textlong);

            LocationManager lm =   (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            LocationListener ll = new mylocationlistener();
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
        }
        class mylocationlistener implements LocationListener{

            @Override
            public void onLocationChanged(Location location) {

                if(location!=null)
                {
                    double lat = location.getLatitude();
                    double lng = location.getLongitude();

                    textlat.setText(Double.toString(lat));
                    textlong.setText(Double.toString(lng));
                }
            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }
            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                // TODO Auto-generated method stub
            }
        }
    }

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textlat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="16dp"
    android:text=""
    android:ems="10">
</TextView>

<TextView
    android:id="@+id/textlong"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:text=""
    android:ems="10">
</TextView>

</RelativeLayout>

AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.checkinapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.checkinapp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

I'm trying to display the latitude and longitude of user to a textview. But I'm not getting the result. Thanks.

VeNaToR
  • 97
  • 1
  • 3
  • 10
  • what is the problem? is you onLocationChanged() method is getting called? is the device GPS on? can you may be try to move near window or out of office to see if you can catch the GPS satellite.. – Praful Bhatnagar Jun 25 '13 at 06:13
  • Consider using the Google Play Services Location APIs, they're better tuned to save battery. – Lesleh Jun 25 '13 at 06:17
  • It is working now.Thanks for the replies. – VeNaToR Jun 25 '13 at 07:04

5 Answers5

10

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
 */
public class GpsLocationTracker extends Service implements LocationListener
{

    /**
     * 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
     */
    private double mLatitude;

    /**
     * longitude
     */
    private double mLongitude;

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

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

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


    /**
     * @param mContext constructor of the class
     */
    public GpsLocationTracker(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
     */
    public void stopUsingGps() {

        if (mLocationManager != null) {

            mLocationManager.removeUpdates(GpsLocationTracker.this);

        }
    }

    /**
     * @return latitude
     *         <p/>
     *         function to get latitude
     */
    public double getLatitude() {

        if (mLocation != null) {

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

    /**
     * @return longitude
     *         function to get longitude
     */
    public double getLongitude() {

        if (mLocation != null) {

            mLongitude = mLocation.getLongitude();

        }

        return mLongitude;
    }

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

        return this.canGetLocation;
    }

    /**
     * function to prompt user to open
     * settings to enable gps
     */
    public void showSettingsAlert() {

        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() {

            public void onClick(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() {

            public void onClick(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 stub
        return null;
    }

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(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-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Dixit Patel
  • 6,179
  • 1
  • 31
  • 42
  • 3
    I don't understand why `GpsLocationTracker` needs to be a [Service](https://developer.android.com/reference/android/app/Service.html). Because it's used with neither [`startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)) nor `bindService()`. – tudorpavel Aug 25 '15 at 11:31
  • 1
    If ACCESS_FINE_LOCATION is specified, the ACCESS_COARSE_LOCATION is redundant. From the documentation: Note: If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only - the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. - (Permission for ACCESS_COARSE_LOCATION includes permission only for NETWORK_PROVIDER.) – ONE May 11 '19 at 21:26
1
LocationManager manager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); 
Location loc =   manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

Toast.makeText( getApplicationContext(),"My current location is: " + "Latitud =" +
  loc.getLatitude() + "Longitud = " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
  • This is the simplest answer that just works. We can add error checks etc to improve but this answer should get more upvotes. – Mudit Verma Nov 01 '20 at 22:22
0

Try this,

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                String provider = locationManager.getBestProvider(criteria,
                        true);
                Location location = locationManager
                        .getLastKnownLocation(provider);
                if (location != null) {
                    onLocationChanged(location);
                }
                // updates location 30seconds once
                locationManager
                        .requestLocationUpdates(provider, 30000, 0, this);
Sreedhu Madhu
  • 2,390
  • 2
  • 28
  • 38
0

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

public class LocationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

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

        try {      
            Bundle b=intent.getExtras();

            LocationPollerResult locationResult = new LocationPollerResult(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());
        }
    }
Mayank Saini
  • 2,977
  • 23
  • 25
0

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

122user321
  • 211
  • 1
  • 4
  • 12