无法正确检索GPS位置

时间:2013-05-29 07:32:30

标签: android

我是android开发新手,我了解android活动生命周期。请参阅以下代码。

    public class MyTest extends Activity{

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

        cont = getApplicationContext();
        final MyLocation my_loc = new MyLocation ();
        my_loc.initialize(cont);

        myMethod();
        }

    Public void myMethod()
    {
       //here when I retrieve the values, it always shows 0.0.
    }
}

    public class MyLocation implements LocationListener {
        public double user_lat;
        public double user_lng;
        private LocationManager locationManager;
        private Context ctx;

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            user_lat = location.getLatitude();
            user_lng = location.getLongitude();     

            //here i save the values for constands to use in myMethod                           
            }
        }

        public void initialize(Context context) {
            this.ctx = context;
            locationManager = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0, this);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                    0, this);
        } 
}

为什么我无法初始化GPS并在同一活动中检索长值和纬度值?

3 个答案:

答案 0 :(得分:3)

LocationClient是获取GPS的新方式。有关最近更新的完整详情,请观看video

请注意,LocationManager的处理方式有问题,因为需要为GPS和NETWORK提供商添加大量代码。新的方式(谷歌内部称为融合位置提供商)与传感器配合使用可大大减少电池消耗。此外,还减少了对复杂API和阶段性选择最佳提供商的需求。只需2-3行代码即可完成。

对于许多三星手机(包括Y型号),虽然有一个特定的问题,大多数时候他们根本没有返回位置。因此,您需要启动该手机才能返回GPS。为此,您可以使用

HomeScreen.getLocationManager().requestLocationUpdates(
    LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(final Location location) {
        }
    });

然后拨打locationClient.getLastLocation api。就像上面的代码一样,就在您的LocationClient.getLastLocation或LocationManager.getLastKnownLocation调用之前

请注意,三星是高度定制的Android开源产品。谷歌无法回应三星相关的漏洞,三星没有任何与Android开发者相关的支持。

编辑:观看视频,相信我,不知道LocationClient给你什么,你不会欣赏这一变化。您还将了解GeoFenceing。

答案 1 :(得分:1)

为了解决您的位置问题,我建议您另一种检索位置的新方法。

检查出来:google play util

下面的代码只是一个片段,而不是完全;)。您不再需要处理gps /网络提供商。它为您处理,哪一个是最好的并返回一个位置。

LocationClient mLocationClient = new LocationClient(...)
mLocationClient.connect();
...
onConnected(Bundle ...){
LocationRequest request = LocationRequest.create();
request.setNumUpdates(1);
...
mLocationClient.requestLocationUpdates(request, new LocationListener....)
....

}

答案 2 :(得分:0)

我为此做了一项服务。使用它可以轻松获得经度/纬度。

在项目中复制/粘贴此类。

package com.sample;
    import com.sample.globalconstant;
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;
    import android.widget.Toast;

    public class MyServiceGPS extends Service
    {
        private static final String TAG = "BOOMBOOMTESTGPS";
        private LocationManager mLocationManager = null;
        private static final int LOCATION_INTERVAL = 1000;
        private static final float LOCATION_DISTANCE = 10f;

        private class LocationListener implements android.location.LocationListener{
            Location mLastLocation;
            public LocationListener(String provider)
            {
                Log.e(TAG, "LocationListener " + provider);
                mLastLocation = new Location(provider);
            }
            public void onLocationChanged(Location location)
            {
                Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude());
                globalconstant.lat  = location.getLatitude();
                globalconstant.lon  = location.getLongitude();
                Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show();
                mLastLocation.set(location);
            }
            public void onProviderDisabled(String provider)
            {
                Log.e(TAG, "onProviderDisabled: " + provider);           
            }
            public void onProviderEnabled(String provider)
            {
                Log.e(TAG, "onProviderEnabled: " + provider);
            }
            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                Log.e(TAG, "onStatusChanged: " + provider);
            }
        }
        LocationListener[] mLocationListeners = new LocationListener[] {
                new LocationListener(LocationManager.GPS_PROVIDER),
                new LocationListener(LocationManager.NETWORK_PROVIDER)
        };
        @Override
        public IBinder onBind(Intent arg0)
        {
            return null;
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
            Log.e(TAG, "onStartCommand");
            super.onStartCommand(intent, flags, startId);      
            return START_STICKY;
        }
        @Override
        public void onCreate()
        {
            Log.e(TAG, "onCreate");
            initializeLocationManager();
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[1]);

            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "network provider does not exist, " + ex.getMessage());
            }
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[0]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "gps provider does not exist " + ex.getMessage());
            }
        }
        @Override
        public void onDestroy()
        {
            Log.e(TAG, "onDestroy");
            super.onDestroy();
            if (mLocationManager != null) {
                for (int i = 0; i < mLocationListeners.length; i++) {
                    try {
                        mLocationManager.removeUpdates(mLocationListeners[i]);
                    } catch (Exception ex) {
                        Log.i(TAG, "fail to remove location listners, ignore", ex);
                    }
                }
            }
        }
        private void initializeLocationManager() {
            Log.e(TAG, "initializeLocationManager");
            if (mLocationManager == null) {
                mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            }
        }
    }

如果要开始,请在“活动”中复制此代码:

startService(new Intent(this,MyServiceGPS.class));

创建一个类globalconstant:

public class globalconstant { public static double lat, lon; }

如果您希望项目中的当前纬度和经度仅写下此globalconstant.lat ,globalconstant.lon

添加uses-permission in Manifest