【问题标题】:Getting coordinates when GPS is fixed - AndroidGPS固定时获取坐标 - Android
【发布时间】:2015-04-10 22:02:39
【问题描述】:

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

    } 

}

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

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

【问题讨论】:

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


    【解决方案1】:

    检查您的代码后,我建议您更正两个:

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

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

    【讨论】:

    • 和nekoexmachina一样。非常感谢。我上面写的我需要明天理解好并在我的代码中做一些排序。
    • 如果您还有其他不明白的地方,请编辑您的问题。如果可以的话,我会帮你的。
    • 我非常感谢您的帮助和 Mikhail Krutov 的帮助。我用一个问题编辑了我的答案。我有更多问题,但我忘记了;-)。如果可以的话,我会给你和米哈伊尔声誉,但我现在不能。
    【解决方案2】:

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

    【讨论】:

    • 非常感谢,我实现了这个类并且位置更改效果很好 - 只有坐标有时会有更多的数字,比如 16.653453333338。明天我将尝试更好地理解该代码。很高兴得到你的帮助,如果有什么麻烦我明天就写到这里。
    【解决方案3】:

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

    android 上的活动有一个适当的lyfecycle。你可以检查here。当活动来自后台时调用 onResume ,而且在创建活动时(在 onCreate 调用之后)。您可以在我提供的链接上查看。

    我也检查了您的代码,对我来说似乎没问题。如果出现一些意外行为,请询问:)

    【讨论】:

    • 感谢 developer.android.com 上的精美图片。我大概4个月前开始学习Java和android,但最近两个月没有太多时间,所以我忘记了很多东西。我应该重读基础知识。我会问你,如果我有什么问题。再次感谢:-)
    • 嗨 Ze Luis,我正在测试这个应用程序,并在某些设备上进行了一些更改。而且我在某些设备上的 setUpMapIfNeeded 中得到了 nullpointerexception(来自 9 的 3 个设备给了我异常)。所有设备都有 android 4 或更高版本。你知道可能是什么问题吗?我没有错误行,但我在 setUpMapIfNeeded 中是怎么说的。如果您知道这是什么问题,我将创建一个新线程,并为您检查正确答案。再次感谢
    • 您是在真机还是模拟器上测试?要使用地图,设备必须具有 google play 服务。请检查一下
    • 在真实设备上测试。我的华为honor 3c好用,女朋友联想好用,索尼xperia(idk型号)好用,华硕zenfone 2好用。三星 Galaxy Note 2 不工作,和小米 mi2s 和索尼 xperia L 一样。小米和我的荣誉有相同版本的谷歌播放服务(所以这不是问题)。除了最重要的地图活动之外,应用程序都可以工作
    • 这是一个问题。我忘记了保存该输出,并且我没有在家中无法使用应用程序的设备。当我回到三星 Galaxy Note 2 时,我会发送输出。现在非常感谢。
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多