1

I tried to get latitude and longitude for current location. However, when I use the code below, the location listener is not triggered at all. I've added the LOCATION permission in manifest file.

anyone can help?

Here is the java code:

package com.example.setlocaction;


import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity{
double latitude, longitude, radius;
LocationManager mlocManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Acquire a reference to the system Location Manager 
    mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);  
    // Define a listener that responds to location updates 
    LocationListener locationListener = new LocationListener() 
    {     
        public void onLocationChanged(Location loc) 
        {      
            // Called when a new location is found by the network location provider.       
            Log.i("loc","location changed");
            if (loc!=null)
            {
                loc.getLatitude(); 
                loc.getLongitude(); 
                String Text = "My current location is: " + 
                "Latitud =" + loc.getLatitude() + 
                "Longitud = " + loc.getLongitude(); 
                Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show(); 

            }
        }      
        public void onStatusChanged(String provider, int status, Bundle extras) 
        {}      
        public void onProviderEnabled(String provider) 
        {}      
        public void onProviderDisabled(String provider) 
        {}   
    };              

    Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);  
        // 高精度  
        criteria.setAltitudeRequired(false);  
        criteria.setBearingRequired(false);  
        criteria.setCostAllowed(true);   
        criteria.setPowerRequirement(Criteria.POWER_LOW);  
        String provider = mlocManager.getBestProvider(criteria, true);
    mlocManager.requestLocationUpdates(provider, 2000, 0, locationListener); 
    Location loc=mlocManager.getLastKnownLocation(provider);
    if (loc==null)
    {
        Log.i("loc","loc=null");
    }
}

}

mafinest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.setlocaction"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.setlocaction.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>

sam
  • 99
  • 2
  • 9
  • post your manifest code here – Sanket Shah Aug 01 '13 at 09:34
  • You'll need COARSE + FINE locations allowed in the Manifest and the time you give it - 2000 ms, which is 2 seconds is not enough even for a NETWORK_PROVIDER. Axpand this to 20000 ms and try again. – g00dy Aug 01 '13 at 09:39
  • @David I've edit the question and post the manifest code. – sam Aug 01 '13 at 09:53
  • put log at isProviderEnable and check it – Kalpesh Lakhani Aug 01 '13 at 10:03
  • see my posted answer .. – Sanket Shah Aug 01 '13 at 10:13
  • @David I used your code in stackoverflow.com/a/17290348/2399772. However it always get the latitude and longitude is 0.0, 0.0. why? – sam Aug 01 '13 at 12:00
  • have you gave any permission in your manifest??? and just go to setting>LocationService> and click yes at Access to my Location on your device. – Sanket Shah Aug 01 '13 at 12:05
  • @g00dy I have make it 60000ms, but when I debug it. after following codes "mlocManager.requestLocationUpdates(provider, 60000, 0, locationListener); Location loc=mlocManager.getLastKnownLocation(provider);", the loc is still null. – sam Aug 01 '13 at 12:08
  • Ok then 1. Check if you have received something in the `provider` (this could be null as well) 2. If the provider is returned, but never used for Location purposes, then the `getLastKnownLocation()` will return be also null. – g00dy Aug 01 '13 at 12:13
  • @g00dy the provider is not null, value is "gps". Then you mean in " Location loc=mlocManager.getLastKnownLocation(provider)", provider was not used for location? – sam Aug 01 '13 at 12:23
  • @David sure, please check my manifest file under the original question, I added it. The wierd thing is that I can get latitude and longitude by googlemap api, but why it didn't work by android itself. – sam Aug 01 '13 at 12:25

4 Answers4

1

First of all, your current solution utilizes "getLastKnownLocation" which means, that if you actually retrieve the longitude and latitude, you cannot be certain that it will return the current position of the user. It simply returns the location which was last found which can be miles away.

That is nothing wrong in doing so, but it leaves for uncertainty.

Instead, I have personally implemented a location manager for retrieving the current position of the user by utilizing the code provided in the following post which works great:

https://stackoverflow.com/a/17290348/2399772

By using this specific code, you will also be given the advantage that it tries to utilize the WiFi connection first for determining the position which is slightly better. It that doesn't work, it will utilize the GPS instead. Additionally, if GPS services aren't enabled, a dialogue will be shown telling the user to enable those.

Hope this helps.

Additional notes As I have stated in a previous post, the Geolocation API will does unfortunately not work on all devices. You can hereby consider using the Reverse Geocoding API instead, which is additionally much more reliable:

https://developers.google.com/maps/documentation/geocoding/

It simply requires that you send a HTTP request which should contain latitude and longitude, whereafter it will provide a response in JSON which is easily parsed.

Community
  • 1
  • 1
Demitrian
  • 3,200
  • 1
  • 24
  • 41
  • thanks David, I used your code in http://stackoverflow.com/a/17290348/2399772. However it always get the latitude and longitude is 0.0, 0.0 – sam Aug 01 '13 at 10:49
  • Yes, that happens if you are indoors and using GPS to find your position and havn't turned on WiFi positioning services; the GPS will hereby have issues finding your location since it isn't very reliable. That's although not an issue with the code itself, but much rather the quality of the GPS. The code hereby seems to be working correctly. Try turning on the WiFi positioning services and tell me whether or not it worked; it normally does the trick for me :) – Demitrian Aug 01 '13 at 12:30
  • I've turned on the wifi and 3G data, when I debug it, don't know why the LocationManager.NETWORK_PROVIDER always returned “false”. So I can only use GPS. I changed your code a little and luckily it worked. – sam Aug 01 '13 at 15:32
  • I am not certain why you encounter the issue when you have WiFi location services enabled. If you have added all of the necessary permissions in your Android Manifest, you should not experience the issue; I do not at least. Note that it isn't exactly my code, but I found inspiration from it as well for my own purpose :) Hope it helped. Please don't forget to vote and set as accepted answer if it helped you out; I'd appreciate it. – Demitrian Aug 01 '13 at 18:22
0

Sometimes it takes a while for the device to deliver the first locations if you haven't used the GPS before. Also, make sure you're in a location where you can gps updates, or try on the emulator using geo fix via telnet.

JohanShogun
  • 2,956
  • 21
  • 30
0

try this

  public class MyLocationActivity extends Activity implements LocationListener {
        private LocationManager mgr;
        private String best;
        public static double myLocationLatitude;
        public static double myLocationLongitude;

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

            mgr = (LocationManager) getSystemService(LOCATION_SERVICE);

            dumpProviders();

            Criteria criteria = new Criteria();

            best = mgr.getBestProvider(criteria, true);
            Log.d("best provider", best);

            Location location = mgr.getLastKnownLocation(best);
            dumpLocation(location);

                //may be some intent here
        }

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

        }

        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

        }

        @Override
        protected void onPause() {

            super.onPause();
            mgr.removeUpdates(this);
        }

        @Override
        protected void onResume() {

            super.onResume();
            mgr.requestLocationUpdates(best, 15000, 1, this);
        }

        private void dumpLocation(Location l) {

            if (l == null) {

                myLocationLatitude = 0.0;
                myLocationLongitude = 0.0;
            } else {

                myLocationLatitude = l.getLatitude();
                myLocationLongitude = l.getLongitude();
            }
        }

        private void dumpProviders() {

            List<String> providers = mgr.getAllProviders();
            for (String p : providers) {

                dumpProviders(p);
            }
        }

        private void dumpProviders(String s) {

            LocationProvider info = mgr.getProvider(s);
            StringBuilder builder = new StringBuilder();
            builder.append("name: ").append(info.getName());
        }

    }
The Ray of Hope
  • 738
  • 1
  • 6
  • 16
0

Add following code to your java file

private void GetLocation() 
            {
                LocationDetail pref_LocationDetail = new LocationDetail(_context);
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                if(objCommon.isOnline(_context)) 
                {
                    if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
                    {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER , 
                                MINIMUM_TIME_BETWEEN_UPDATES,
                                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, 
                                new MyLocationListener()    
                                );

                        return ; 
                    }
                    else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                    {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER , 
                                MINIMUM_TIME_BETWEEN_UPDATES,
                                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, 
                                new MyLocationListener()    
                                );

                        return ;
                    }
                }
            }

            private class MyLocationListener implements LocationListener 
            {

                public void onLocationChanged(Location location) 
                {
                    LocationDetail pref_LocationDetail = new LocationDetail(_context);


                        double Lattitude = location.getLatitude(); 
                        double Longitude =  location.getLongitude();



                    Toast.makeText(_context  , location.getProvider().toString() , Toast.LENGTH_LONG).show();

                    locationManager.removeUpdates(this);  
                    locationManager = null;                                                                                            
                }

                public void onStatusChanged(String s, int i, Bundle b) {
                    Toast.makeText(_context , "Provider status changed",  
                            Toast.LENGTH_LONG).show();   
                }

                public void onProviderDisabled(String s) {
                    Toast.makeText(_context ,
                            "Provider disabled by the user. GPS  turned off",
                            Toast.LENGTH_LONG).show();     
                }

                public void onProviderEnabled(String s) {    
                    Toast.makeText(_context ,
                            "Provider enabled by the user. GPS turned on", 
                            Toast.LENGTH_LONG).show();
                }
            }

just add following code in your manifest

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
Sanket Shah
  • 4,352
  • 3
  • 21
  • 41