android requestLocationUpdates失败

时间:2013-10-24 07:33:45

标签: android google-maps

我正在开发一个与接近警报相关的项目。为此,每当我打开我的应用程序时,我都需要准确读取我的位置。即使我遵循android文档规定的正确编码实践,我也没有得到预期的结果。

为什么在getLastKnownLocation的整个android Geolocation编码中没有替代命令,这将为我们提供我们之前不在的地方。

我在同一行中做了一个javascript编码。我的代码工作正常。描述性的地址和坐标,我的设备在那里工作很好。那些命令getCurrentPosition和watchPosition通过它们的事件处理程序回调给出了很好的响应。为什么android地理位置说法中没有getCurrentLocation?

即使我已经遵循相关的编码实践,当我从一个地方移动到另一个地方时,实现LocationListener的MyLocationListener myLocationUpdate也没有更新我的新位置。我将MINIMUM_DISTANCE_CHANGE_FOR_UPDATES设为1(以米为单位),将MINIMUM_TIME_BETWEEN_UPDATES设为1000(以毫秒为单位)。

我将在下面提供重要的代码段以了解问题

在活动的onCreate处理程序

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!enabled) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
    }
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    myLocationUpdate = new MyLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationUpdate);
    retrieveLocationButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"Finding Location",Toast.LENGTH_LONG).show();          
        showCurrentLocation();
        }
    });
    latituteField = (TextView) findViewById(R.id.display_Location);

showCurrentLocation();

showCurrentLocation函数中的

我正在使用locationManager.getLastKnownLocation(provider)来检索该位置。 通过使用GeoCoder对象和命令geocoder.getFromLocation(纬度,经度,1)来获得坐标的第一个地址匹配。     //处理位置cahnge事件的内部类     私有类MyLocationListener实现LocationListener包含所有重写函数,包括public void onLocationChanged(Location location)  但实际上我从所有的应用程序中得不到任何东西。我已经通过location.getTime()记录了时间。它显示固定的较早时间,但不是我指定的间隔。

3 个答案:

答案 0 :(得分:0)

我的方式是在我的应用程序中做到这一点,并且工作很好。

  1. 创建AsyncTask线程,该线程将在后台获取位置。

    公共类GPSmanager扩展了AsyncTask实现         LocationListener {

    private Context mContext;
    private final long MIN_TIME_BW_UPDATES = 100000;
    private final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    
    public GPSmanager(Context mContext) {
        super();
        this.mContext = mContext;
    }
    
    public String getCurrentCity() {
        String adress = null;
        try {
            Location location = getLocation();
            Geocoder gcd = new Geocoder(mContext, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(
                    location.getLatitude(), location.getLongitude(), 1);
            if (addresses.size() > 0) {
                for (int i = 0; i < addresses.size() && adress == null; i++)
                    adress = addresses.get(i).getLocality();
                for (int i = 0; i < addresses.size() && adress == null; i++)
                    adress = addresses.get(i).getCountryName();
                Intent intent = new Intent(MainActivity.BRODCAST_ACTION);
                intent.putExtra("city", adress);
                mContext.sendBroadcast(intent);
                return adress;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return adress;
    }
    
    private Location getLocation() {
        Location location = null;
        try {
            LocationManager locationManager = (LocationManager) mContext
                    .getSystemService(Context.LOCATION_SERVICE);
    
            // getting GPS status
            boolean isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
            // getting network status
            boolean isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                try {
                    Looper.prepare();
                } catch (Exception e) {
                }
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        }
                    }
                }
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return location;
    }
    
    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    protected Void doInBackground(Void... params) {
        getCurrentCity();
        return null;
    }
    
  2. 创建服务并在服务中运行此线程

    public class UpdatesService extends Service {
    private GPSmanager gpsManager;
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        gpsManager = new GPSmanager(this);
        Utiles.taskLauncher(gpsManager);
    
        return super.onStartCommand(intent, flags, startId);
    }
    

    }

  3. 在您需要该位置的Activity中注册BrodcastReciver。

    私有BroadcastReceiver receiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BRODCAST_ACTION)) {
                String city = intent.getExtras().getString("city");
                if (city != null)
                    if (!city.isEmpty())
                        etSearchCity.setText(intent.getExtras().getString(
                                "city"));
            }
        }
    };
    
  4. 在onCreate中注册。

        registerReceiver(receiver, new IntentFilter(BRODCAST_ACTION));
    
  5. 有最好的方法,我发现这样做。在后台快速完成任务的唯一方法 - 使用Service。 P.S不要忘记在你的清单中添加服务。

答案 1 :(得分:0)

获取GPS位置的问题在于它不能立即使用。根据我对GPS位置提供程序的理解,当您请求位置更新时,gpr提供程序将尝试连接到在单独的线程中运行的gps卫星(不完全确定它)。在此期间,您的程序正常执行,并且您可能无法获得任何位置。

您可以使用今年IO事件中引入的融合位置提供。您可以找到教程here

答案 2 :(得分:0)

使用此功能查找当前位置

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;



import android.util.Log;


  public class GetMyLocation extends Service implements LocationListener {

    Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1 meter

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 500; // 0.5 second

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GetMyLocation(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GetMyLocation.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will launch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }


}

在您的活动中使用它

gps = new GetMyLocation(YourActivity.this);

                    // check if GPS enabled     
                    if(gps.canGetLocation()){

                        latitude = gps.getLatitude();
                        longitude = gps.getLongitude();

                    }
                    else{
                        // can't get location
                        // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings

                        gps.showSettingsAlert();
                    }