1
    public class LocationtesterActivity extends Activity {
        /** Called when the activity is first created. */
        LocationManager locManager;
        // LocationListener locListener;
        Button b;
        String provider;
        TextView lat, alt, longi;


// Here i am first checking if both GPS and network options are enabled in Lovation and Security Settings or not.

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            b = (Button) findViewById(R.id.button1);
            lat = (TextView) findViewById(R.id.lattitude);
            alt = (TextView) findViewById(R.id.altitude);
            longi = (TextView) findViewById(R.id.longitude);

            b.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    showCurrentLocation();

                }

            });

            locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);

            criteria.setPowerRequirement(Criteria.POWER_LOW);

            provider = locManager.getBestProvider(criteria, true);

            System.out.println("best provider is :" + provider);

            if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
                    || !locManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                System.out.println("in provider enablement");
                createGpsDisabledAlert();

            }

            else {
                System.out.println("in location update request");
                locManager.requestLocationUpdates(provider, 0, 0,
                        new MyLocationListener());

            }

        }

        // for displaying the Dialogue Box
        // if GPS or network not enabled
        // and also taking to location and security screen

        private void createGpsDisabledAlert() {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(
            "Your GPS or network provider is disabled! Would you like to enable it?")
            .setCancelable(false)
            .setPositiveButton("Enable provider",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    showGpsOptions();
                }
            });
            builder.setNegativeButton("Do nothing",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }

        private void showGpsOptions() {
            Intent gpsOptionsIntent = new Intent(
                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(gpsOptionsIntent, 5);
        }

        // //////ends/////

        // Code to check whether user enabled GPS and Network provider in settings
        // if not then show the dialogue box again

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == 5 && resultCode == 0) {
                if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    createGpsDisabledAlert();
                    // Toast.makeText(this,
                    // "provider not enabled. Click the button for settings",
                    // 2000).show();
                } else {

                    Intent i=new Intent(this, LocationtesterActivity.class);
                    startActivity(i);
                    Toast.makeText(this, "User has enabled the provider", 1000)
                    .show();

                }
            }
        }

        // Method to display the current location
        protected void showCurrentLocation() {

            Location location = locManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);

            if (location != null) {

                String message = String.format(

                        "Current Location \n Longitude: %1$s \n Latitude: %2$s",

                        location.getLongitude(), location.getLatitude()

                );

                lat.setText("" + location.getLatitude());
                longi.setText("" + location.getLongitude());

                Toast.makeText(LocationtesterActivity.this, message,

                        Toast.LENGTH_LONG).show();

            }
            else
            {
                Toast.makeText(LocationtesterActivity.this, "no last known location", 1000).show();
            }

        }

        // Inner class for LocationListener
        private class MyLocationListener implements LocationListener {

            public void onLocationChanged(Location location) {


                System.out.println("in location changed");

                String message = String.format(

                        "New Location \n Longitude: %1$s \n Latitude: %2$s",

                        location.getLongitude(), location.getLatitude()

                );
                lat.setText("" + location.getLatitude());
                longi.setText("" + location.getLongitude());
                // alt.setText("" + location.getAltitude());
                Toast.makeText(LocationtesterActivity.this, message,
                        Toast.LENGTH_LONG).show();

            }

            public void onStatusChanged(String s, int i, Bundle b) {

                Toast.makeText(LocationtesterActivity.this,
                        "Provider status changed",

                        Toast.LENGTH_LONG).show();

            }

            public void onProviderDisabled(String s) {

                Toast.makeText(LocationtesterActivity.this,

                        "Provider disabled by the user. GPS turned off",

                        Toast.LENGTH_LONG).show();

            }

            public void onProviderEnabled(String s) {

                Toast.makeText(LocationtesterActivity.this,

                        "Provider enabled by the user. GPS turned on",

                        Toast.LENGTH_LONG).show();

            }

        }

    }

I am using the above code to find the User Location. 1.I am getting always GPS as the best provider according to my criteria but that is fine to me. 2.Thing is that why am i not able to get any location values ? Even with Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); i am not getting any thing. Please help me in getting the location values.

  • if you are checking in mobile(device) Location location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) try this for initial loading and be on move to get updated values with gps on!! – Chet Jan 09 '12 at 06:11
  • With network Provider it's working but with GPS it's not working even if i wait for 10 mints. – sachin_ahuja Jan 09 '12 at 07:09
  • change this to locManager.requestLocationUpdates(provider, 0, 0, new MyLocationListener()); to ........ locManager.requestLocationUpdates(provider, 8000, 2, new MyLocationListener());... 8000(time[millisec] req for update..) and 2 specifies meters... – Chet Jan 09 '12 at 15:57

2 Answers2

0

GPS take some time due to slow and not available inside the building .You just check it outside the building.
And Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); only works if once GPS get any location previously.

deepak Sharma
  • 1,641
  • 10
  • 23
  • 1
    :- Thanks for the info. But problem is that after 5 mins or 10 mins also i have invoked the same method but i am not able to display any values. – sachin_ahuja Jan 09 '12 at 07:06
  • http://stackoverflow.com/questions/5124525/current-gps-location-in-android visit this site may be you find your solution – deepak Sharma Jan 09 '12 at 07:11
-1

Two things,

  1. Have u set "android.permission.ACCESS_FINE_LOCATION" permission in manifest file ??

  2. clear all data of Google map application and then try to load map for get current location on map, If Google map give your current location then your application can fetch current location.

Its good habit to use best criteria for fetching location.

sometimes devices can not read current location. I also face this problem but at that time i check Google Map / Direction application and reset my GPS.

rajpara
  • 5,203
  • 1
  • 29
  • 46
  • I have added the permissions:- – sachin_ahuja Jan 09 '12 at 11:36
  • I have added the permissions:- "android.permission.ACCESS_COARSE_LOCATION" "android.permission.ACCESS_FINE_LOCATION" "android.permission.ACCESS_MOCK_LOCATION" "android.permission.INTERNET" "android.permission.CONTROL_LOCATION_UPDATES" "android.permission.ACCESS_WIFI_STATE" "android.permission.ACCESS_NETWORK_STATE" and i have also loaded Google Maps. It's showing My Location in it. I am using android 2.2 for it. Aand i have tried the project with both Android 2.2 APIs and Google Inc APIs 2.2. DO i need something else for it. – sachin_ahuja Jan 09 '12 at 11:42
  • you must use google API. Why u insist for GPS provider, if u can fetch location with help of network provider then what is issue in it ?? – rajpara Jan 09 '12 at 12:48
  • 1
    actually it's requirement , that i have to use GPS. – sachin_ahuja Jan 10 '12 at 04:53