0

我正在开发一个接近警报相关的项目。为此,每当我打开我的应用程序时,我都需要准确了解我的位置。即使我遵循 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 函数中,我使用 locationManager.getLastKnownLocation(provider) 来检索该位置。通过使用 GeoCoder 对象和命令 geocoder.getFromLocation(latitude, longitude, 1) 来获取坐标的第一个地址匹配。// 处理位置变化事件的内部类 private 类 MyLocationListener 实现 LocationListener 包含所有重写的函数,包括 public void onLocationChanged(Location location) 但实际上我从所有应用程序中什么都得不到。我已经通过 location.getTime() 记录了时间。它显示了一个固定的较早时间,但不是我指定的时间间隔。

4

3 回答 3

0

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

你可以做的是使用在今年的 IO Event 中引入的 Fused Location Provide。你可以在这里找到教程

于 2013-10-24T07:55:34.193 回答
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。

    私人广播接收器接收器=新广播接收器(){

        @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. 有最好的方法,我发现可以做到。在后台快速完成此操作的唯一方法 - 使用服务。PS 不要忘记在您的清单中添加服务。

于 2013-10-24T07:51:25.600 回答
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();
                    }
于 2013-10-24T07:57:43.213 回答