在GPS修复时获取坐标 - Android

时间:2015-02-10 18:24:36

标签: android gps google-maps-android-api-2 locationmanager

我正在尝试在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();

    } 

}

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

在onCreate中我怎么可能不需要setUpMapIfNeeded方法?我认为onResume仅在应用程序背景时才有效。

3 个答案:

答案 0 :(得分:2)

至少使用onLocationChanged方法实现位置监听器。 http://developer.android.com/reference/android/location/LocationListener.html

答案 1 :(得分:2)

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

1 - 完成您的criteria。您将它传递给locationManager实例。 2 - 使用LocationListener api实现您的目标。您可以找到here一些帮助。

编辑:从setUpMapIfNeeded()方法移除onCreate的来电。这实际上是被调用两次(在onCreate和onResume()中)。

答案 2 :(得分:0)

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

Android上的活动有一个正确的 lyfecycle 。您可以查看here。当活动来自后台时,也会在创建时(在onCreate调用之后)调用onResume。您可以在我提供的链接上查看。

我也检查了你的代码,对我来说似乎很好。如果出现一些意想不到的行为,请问:)