无法获得纬度和经度

时间:2013-08-01 09:29:29

标签: android geolocation location

我试图获取当前位置的纬度和经度。 但是,当我使用下面的代码时,根本不会触发位置监听器。 我在清单文件中添加了LOCATION权限。

任何人都可以提供帮助吗?

这是java代码:

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>

4 个答案:

答案 0 :(得分:1)

首先,您当前的解决方案使用“getLastKnownLocation”,这意味着,如果您实际检索经度和纬度,您无法确定它是否会返回当前位置用户。它只返回最后找到的位置,可以在几英里之外。

这样做没有错,但它留下了不确定性。

相反,我亲自为检索用户的当前位置实施了一个位置管理器,利用以下帖子中提供的代码非常有效:

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

通过使用此特定代码,您还将获得优势,即它首先尝试利用WiFi连接来确定稍微好一点的位置。它不起作用,它将使用GPS代替。此外,如果未启用GPS服务,将显示一个对话框,告知用户启用这些服务。

希望这有帮助。

附加说明 正如我在上一篇文章中所说,Geolocation API will does unfortunately not work on all devices。您可以考虑使用反向地理编码API,这样更可靠:

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

它只需要您发送一个应包含纬度和经度的HTTP请求,然后它将在JSON中提供一个易于解析的响应。

答案 1 :(得分:0)

如果您以前没有使用GPS,有时需要一段时间才能传送第一个位置。此外,请确保您所在的位置可以进行gps更新,或者通过telnet使用地理位置修复模拟器。

答案 2 :(得分:0)

试试这个

  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());
        }

    }

答案 3 :(得分:0)

将以下代码添加到您的java文件

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();
                }
            }

只需在清单

中添加以下代码即可
  <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" />