получить местоположение мгновенно в Android - PullRequest
0 голосов
/ 14 мая 2011

Я хочу нажать кнопку и получить текущее местоположение, я понимаю, что не могу сразу получить местоположение, поэтому я сделал следующее: событие клика:

        public void onClick(View v)
        {
            ProgressDialog MyDialog = ProgressDialog.show( MainPage.this, " " , " Loading. Please wait ... ", true);
            MyActionsHandler myActionsHandler = new myActionsHandler(MainPage.this);
            myActionsHandler.startSearch();
            MyDialog.dismiss();
            Intent intent = new Intent(MainPage.this, ResultPage.class);
            startActivity(intent);
        }

и это обработчик, который ищет местоположение

    public void startSearch(long timeInterval,float distanceInterval)
{
    LocationManager lm = (LocationManager)_context.getSystemService(Context.LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, timeInterval,
            distanceInterval, this);

    while(!_locationFound)
    {
        //wait till location is found
    }
}

public void onLocationChanged(Location location)
{
    if (location != null)
    {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        float speed = location.getSpeed();
        float bearing = location.getBearing();

        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        try
        {
            doTheProcess(_searchType,latitude, longitude, speed, bearing);
           _locationFound = true;
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Я понимаю, что это не работает, потому что цикл находится в том же потоке, так что вы предлагаете лучшее решение для этого?

в javadoc requestLocationUpdates есть «Вызывающий поток должен быть потоком Looper, таким как основной поток вызывающего Activity». но я не нашел ни одного примера, поэтому я не знаю, правильное ли это решение.

еще один вопрос, getLastKnownLocation() работает, даже если я никогда раньше не вызывал locationManager? спасибо

Ответы [ 3 ]

3 голосов
/ 07 ноября 2011

У меня такая же проблема раньше ... но у меня есть решение ... это самый простой способ мгновенно определить местоположение.

public class LocationFinder extends Activity {

    TextView textView1;
    Location currentLocation;
    double currentLatitude,currentLongitude;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textView1 = (TextView) findViewById(R.id.textView1);
        Log.i("@@@@@@@@@@ Inside LocationFinder onCreate", "LocationFinder onCreate");

        FindLocation();

    }

    public void FindLocation() {
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                updateLocation(location);

                Toast.makeText(
                        LocationFinder.this,
                        String.valueOf(currentLatitude) + "\n"
                                + String.valueOf(currentLongitude), 5000)
                        .show();

                }

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

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

    }


    void updateLocation(Location location) {
            currentLocation = location;
            currentLatitude = currentLocation.getLatitude();
            currentLongitude = currentLocation.getLongitude();
            textView1.setText(String.valueOf(currentLatitude) + "\n"
                    + String.valueOf(currentLongitude));

        }
}
0 голосов
/ 13 октября 2011

У меня возникло нечто подобное, когда я не мог получать обновления местоположения, смешивая LocationListener с моими собственными Threads / HandlerThreads. Решением было использование PendingIntent и requestLocationUpdates (поставщик, minTime, minDistance, намерение). Взгляните на: Как получать обновления местоположения без использования услуги

0 голосов
/ 14 мая 2011

Вы можете полностью избавиться от переменной _locationFound - что вы изначально собирались иметь в блоке

while(!_locationFound) {}

?

Если вы избавитесь от этого и переместите всепервоначально было бы в этом блоке в вашей функции doTheProcess (или где вы устанавливаете _locationFound в true), тогда он должен работать, я верю.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...