固定 GPS 时获取坐标 - Android

Getting coordinates when GPS is fixed - Android

我正在尝试在 android 上学习使用定位服务。我使用了我找到的最简单的代码,并尝试了解它是如何工作的。但问题是当我想将坐标放入 textView 时。

代码如下:

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找到我的位置,然后把蓝点放到地图上,是怎么得到坐标的?

编辑:

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();

    } 

}

所以,我实现了 Location Listener(我希望我做得很好),但看起来该应用程序有效。如果我理解得很好,首先我会得到比 UpdatePosition 更快的 lastKnownPosition。然后 LocationListener 在位置更改时调用 onLocationChanged 方法。希望我明白了。

我怎么可能不需要 onCreate 中的 setUpMapIfNeeded 方法?我以为 onResume 只有在应用程序后台运行时才有效。

至少用onLocationChanged方法实现Location Listener。 http://developer.android.com/reference/android/location/LocationListener.html

检查您的代码后,我建议您进行两处更正:

1 - 完成你的 criteria。您将其空传递给 locationManager 实例。 2 - 使用 LocationListener api 来实现你想要的。您可以找到 here 一些帮助。

编辑:onCreate 方法中删除对 setUpMapIfNeeded() 的调用。这实际上被调用了两次(在 onCreate 和 onResume() 中)。

为修改后的问题添加新回复:

android 上的 activity 有一个适当的 lyfecycle。您可以检查 here。 onResume 在 activity 来自后台时被调用,也在创建它时(在 onCreate 调用之后)被调用。您可以在我提供的 link 上查看。

我也检查了你的代码,我觉得没问题。如果出现一些意想不到的行为,请问 :)