【问题标题】:Android GPS location services安卓 GPS 定位服务
【发布时间】:2015-10-03 14:35:33
【问题描述】:

我有一个可以跟踪用户位置的安卓应用程序。它已设置为尽可能使用 Wifi/网络位置服务,否则使用 GPS_PROVIDER 服务。当有 wifi 连接时,它可以正常工作,但是当我设置为仅从 GPS 获取位置时,应用程序崩溃。从测试我有行 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);实际上并没有设置位置,而是仍然为空。有谁知道为什么会这样?

 package temp;

    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.content.DialogInterface;
    import android.provider.Settings;
    import android.util.Log;

    import java.util.List;
    import java.util.Locale;

    public class GPSTracker implements LocationListener {
    private Context context;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled;
    Location location;
    boolean canGetLocation = false;
    Geocoder geocoder;
    List<Address> addresses;

    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
    private static  final long MIN_TIME_BW_UPDATES = 5 * 1000;

    protected LocationManager locationManager;

    public GPSTracker(Context context){
        this.context = context;
        getLocation();
    }

    public Location getLocation(){
        try{
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if(!isGPSEnabled && !isNetworkEnabled){
                showSettingsAlert();
            }else{
                this.canGetLocation = true;
                if(isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                            geocoder = new Geocoder(context, Locale.getDefault());
                            this.addresses = geocoder.getFromLocation(latitude, longitude, 1);
                        }
                    }
                }else{
                    Log.e("GPS_Provider: ", "Made it");
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if(locationManager == null){
                        Log.e("GPS_Provider: ", "Manager1");
                    }else{
                        Log.e("GPS_Provider: ", "Manager2");
                    }

                    if(locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if(location == null){
                            Log.e("GPS_Provider: ", "Made it2");
                        }else{
                            Log.e("GPS_Provider: ", "Made it3");
                        }

                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                            Log.e("Cords: ", "latitude: " + latitude + " longitude: " + longitude);

                            geocoder = new Geocoder(context, Locale.getDefault());
                            this.addresses = geocoder.getFromLocation(latitude, longitude, 1);
                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return location;
    }

    public void stopUsingGps(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    public List<Address> getAddress(){
        return this.addresses;
    }

    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
        return  latitude;
    }

    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
        return longitude;
    }

    public boolean canGetLocation(){
        return this.canGetLocation;
    }

    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setTitle("GPS is settings");
        alertDialog.setMessage("GPS is not enabled.");
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(intent);
            }
        });

        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        alertDialog.show();

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
    }

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="temp" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".login"
            android:label="@string/title_activity_login" >
        </activity>
        <activity
            android:name=".Register"
            android:label="@string/title_activity_register" >
        </activity>
    </application>

</manifest>

【问题讨论】:

  • 始终检查getLastKnownLocation() 的结果是否为空,因为它经常为空。此外,您在onLocationChanged() 中没有任何代码,一旦您在调用requestLocationUpdates() 后获得位置锁定,就会调用该代码。另外,请查看此博客条目,该条目对您正在使用的代码进行了深入解释,并提供了另一种方法:gabesechansoftware.com/location-tracking

标签: android gps location


【解决方案1】:

你得到 null 作为回报,因为如果 GPS 从未真正获得最后一个位置,它就什么也没有给你

您可以查看 FusedLocationProviderAPI,而不是 LocationManager 并自己管理连接问题,它利用了可用的最节能的位置轮询方法,并为您完成所有后台工作。

【讨论】:

  • LocationManager.NETWORK_PROVIDER 是如何拥有最后一个已知位置的呢?两者在不同时间抓取位置吗?这也是我最初的想法,但后来这让我很困惑
  • 硬件和设备。 GPS 必须根据卫星对位置进行三角测量,我认为只要网络可用,就可以访问网络,以便适当的蜂窝塔处理通信
  • 所以网络几乎可以立即获取位置,但 gps 需要更长的时间,因此当我尝试获取它尚未找到的位置并返回 null 时?如果我给它更多时间寻找位置,你认为它会起作用吗?目前我刚刚在应用启动后 5 秒尝试过。
  • 您可以这样做,但随后您将进行轮询,直到您得到一个低效且无效的坐标。就像我在答案中所说,尝试 FusedLocationProviderAPI。我在项目进行到一半时进行了转换,这让事情变得更好了。
  • 如果我回答了您的问题,请为其他开发者标记为已解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多