Я пытаюсь изучить работу с сервисом определения местоположения на 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 работает только тогда, когда приложение было задумано.
такой же подобный nekoexmachina. Большое спасибо. Как я писал выше, мне нужно завтра, чтобы понять хорошее и сделать небольшой заказ в моем коде. – Bulva
Если у вас есть что-то еще, что вы не понимаете, отредактируйте свой вопрос. Я помогу тебе, если смогу. –
Я очень благодарен вам за помощь и помощь Михаила Крутова. Я отредактировал свой ответ на один вопрос. У меня было больше вопросов, но я их забыл ;-).Я бы дал вам и репутацию Михаила, если мог, но пока не могу. – Bulva