2015-02-10 6 views
1

Я пытаюсь изучить работу с сервисом определения местоположения на Android. Я использовал самый простой код, который нашел, и попытаюсь узнать, как он работает. Но проблема в том, когда я хочу поместить координаты в textView.Получение координат при фиксированном GPS - Android

Вот код:

package com.example.bakalarka; 

import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.widget.TextView; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 


    public class GPSActivity extends FragmentActivity { 

     private GoogleMap mMap; 
     private TextView txtLat; 
     private TextView txtLng; 
     private TextView category; 

     protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_gps); 
       category = (TextView)findViewById(R.id.category); 
       txtLat = (TextView)findViewById(R.id.tv_latitude); 
       txtLng = (TextView)findViewById(R.id.tv_longitude); 
       category.setText(getIntent().getStringExtra("kategorie")); 
       setUpMapIfNeeded(); 
     } 

     @Override 
     protected void onResume() { 
      super.onResume(); 
      setUpMapIfNeeded(); 
     } 

     private void setUpMapIfNeeded() { 
      // Do a null check to confirm that we have not already instantiated the map. 
      if (mMap == null) { 
       // Try to obtain the map from the SupportMapFragment. 
       mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
         .getMap(); 
       // Check if we were successful in obtaining the map. 
       if (mMap != null) { 
        setUpMap(); 
       } 
      } 
     } 

     private void setUpMap() { 


      // Enable MyLocation Layer of Google Map 
      mMap.setMyLocationEnabled(true); 

      // Get LocationManager object from System Service LOCATION_SERVICE 
      LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

      if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
       buildAlertMessageNoGps(); 
      } 

      // Create a criteria object to retrieve provider 
      Criteria criteria = new Criteria(); 

      // Get the name of the best provider 
      String provider = locationManager.getBestProvider(criteria, true); 

      // Get Current Location 
      Location myLocation = locationManager.getLastKnownLocation(provider); 

      // set map type 
      mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

      // Get latitude of the current location 
      double latitude = myLocation.getLatitude(); 

      // Get longitude of the current location 
      double longitude = myLocation.getLongitude(); 

      // Create a LatLng object for the current location 
      LatLng latLng = new LatLng(latitude, longitude); 

      String stringDoubleLat = Double.toString(latitude); 
      txtLat.setText(stringDoubleLat); 
      String stringDoubleLng = Double.toString(longitude); 
      txtLng.setText(stringDoubleLng); 

      // Show the current location in Google Map 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

      // Zoom in the Google Map 
      mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); 

     } 

     private void buildAlertMessageNoGps() { 
      final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setMessage("Your GPS seems to be disabled, do you want to enable it?") 
        .setCancelable(false) 
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
         public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
          startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
         } 
        }) 
        .setNegativeButton("No", new DialogInterface.OnClickListener() { 
         public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
          dialog.cancel(); 
         } 
        }); 
      final AlertDialog alert = builder.create(); 
      alert.show(); 

     } 

    } 

Так проблема, когда GPS выключен, приложение дает мне неточные координаты конечно, потому что я получаю координаты GPS, прежде чем найти свое местоположение.

Как получить координаты после того, как GPS нашел мое местоположение и поместил синюю точку на карту?

EDIT:

package com.example.locationlistener; 


import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 


import android.support.v4.app.FragmentActivity; 
import android.widget.TextView; 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 


public class MainActivity extends FragmentActivity { 

    private GoogleMap mMap; 
    private TextView txtLat; 
    private TextView txtLng; 
    private LocationManager locationManager; 

    //private TextView category; 

    protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      //category = (TextView)findViewById(R.id.category); 
      txtLat = (TextView)findViewById(R.id.tv_latitude); 
      txtLng = (TextView)findViewById(R.id.tv_longitude); 
      //category.setText(getIntent().getStringExtra("kategorie"));*/ 

      // Get LocationManager object from System Service LOCATION_SERVICE 
      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener); 


    } 
    private final LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      String stringDoubleLat = Double.toString(location.getLatitude()); 
      txtLat.setText(stringDoubleLat); 
      String stringDoubleLng = Double.toString(location.getLongitude()); 
      txtLng.setText(stringDoubleLng); 
     } 

     public void onProviderDisabled(String provider){ 

     } 

     public void onProviderEnabled(String provider){} 

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

     @Override 
    protected void onResume() { 
     super.onResume(); 
     setUpMapIfNeeded(); 

    } 

    private void setUpMapIfNeeded() { 
     // Do a null check to confirm that we have not already instantiated the map. 
     if (mMap == null) { 
      // Try to obtain the map from the SupportMapFragment. 
      mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
        .getMap(); 
      // Check if we were successful in obtaining the map. 
      if (mMap != null) { 
       setUpMap(); 
      } 
     } 
    } 

    private void setUpMap() { 


     // Enable MyLocation Layer of Google Map 
     mMap.setMyLocationEnabled(true); 




     if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      buildAlertMessageNoGps(); 
     } 

     // Create a criteria object to retrieve provider 
     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 
     criteria.setPowerRequirement(Criteria.POWER_HIGH); 

     // Get the name of the best provider 
     String provider = locationManager.getBestProvider(criteria, true); 

     // Get Current Location 
     Location myLocation = locationManager.getLastKnownLocation(provider); 

     // set map type 
     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

     // Get latitude of the current location 
     double latitude = myLocation.getLatitude(); 

     // Get longitude of the current location 
     double longitude = myLocation.getLongitude(); 

     // Create a LatLng object for the current location 
     LatLng latLng = new LatLng(latitude, longitude); 

     String stringDoubleLat = Double.toString(latitude); 
     txtLat.setText(stringDoubleLat); 
     String stringDoubleLng = Double.toString(longitude); 
     txtLng.setText(stringDoubleLng); 

     // Show the current location in Google Map 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

     // Zoom in the Google Map 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); 


    } 


    private void buildAlertMessageNoGps() { 
     final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage("Your GPS seems to be disabled, do you want to enable it?") 
       .setCancelable(false) 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
        public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
         startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
        } 
       }) 
       .setNegativeButton("No", new DialogInterface.OnClickListener() { 
        public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
         dialog.cancel(); 
        } 
       }); 
     final AlertDialog alert = builder.create(); 
     alert.show(); 

    } 

} 

Итак, я реализовал Место Слушатель (я надеюсь, что я сделал это хорошо), но это выглядит, что приложение работает. Если я хорошо понимаю, сначала я получаю lastKnownPosition, который быстрее, чем UpdatePosition. А затем LocationListener вызовет методLocationChanged при изменении местоположения. Надеюсь, я это понимаю.

Как возможно, что мне не нужен setUpMapIfNeeded метод в onCreate? Я думал, что onResume работает только тогда, когда приложение было задумано.

ответ

2

После изучения кода, я предлагаю вам два исправления:

1 - Исполни свой criteria. Вы передаете его пустым в экземпляр locationManager. 2 - Используйте LocationListener api для достижения желаемого. Вы можете найти помощь here.

EDIT: удалить звонок setUpMapIfNeeded() из метода onCreate. Это фактически вызывается дважды (в onCreate и in onResume()).

+0

такой же подобный nekoexmachina. Большое спасибо. Как я писал выше, мне нужно завтра, чтобы понять хорошее и сделать небольшой заказ в моем коде. – Bulva

+0

Если у вас есть что-то еще, что вы не понимаете, отредактируйте свой вопрос. Я помогу тебе, если смогу. –

+0

Я очень благодарен вам за помощь и помощь Михаила Крутова. Я отредактировал свой ответ на один вопрос. У меня было больше вопросов, но я их забыл ;-).Я бы дал вам и репутацию Михаила, если мог, но пока не могу. – Bulva

2

Внесите приемник местоположения с помощью метода onLocationChanged. http://developer.android.com/reference/android/location/LocationListener.html

+0

Большое спасибо, я внедрил этот класс, и изменение местоположения работает хорошо - только координаты имеют когда-то немного больше, например 16.653453333338. Завтра я постараюсь лучше понять этот код. Я очень рад за помощь, я напишу здесь завтра, если у меня возникнут проблемы. – Bulva

0

Добавление нового ответа на модифицированном вопрос:

Активность на андроид имеет надлежащую lyfecycle. Вы можете проверить это here. OnResume вызывается, когда действие происходит из фона, но также и при его создании (после вызова onCreate). Вы можете проверить это на ссылке, которую я предоставил.

Я тоже проверил ваш код, и мне это кажется прекрасным. Если какое-то неожиданное поведение повысится, просто спросите :)

+0

Thx много для красивой картинки на developer.android.com. Я начал изучать Java и android, возможно, 4 месяца назад, но у меня не так много времени в последние два месяца, поэтому я забыл многое. Я должен пересмотреть основы. Я спрошу вас, если у меня возникнут проблемы. Thx снова :-) – Bulva

+0

@Bulva, пожалуйста! :) –

+0

Привет, Ze Luis, я тестировал это приложение с некоторыми изменениями на некоторых устройствах. И я получаю nullpointerexception в setUpMapIfNeeded на некоторых устройствах (3 устройства из 9 дали мне исключение). У всех устройств был Android 4 и выше. Знаете ли вы, что может быть проблемой? У меня нет строки ошибки, но я сказал, что это было в setUpMapIfNeeded. Если вы знаете, в чем проблема, я создам новый поток, и я дам вам чек для правильного ответа. Еще раз спасибо – Bulva

Смежные вопросы