【问题标题】:Why is my android app always giving 0 for the latitude and Longitude?为什么我的 android 应用程序的纬度和经度总是为 0?
【发布时间】:2017-02-12 20:04:52
【问题描述】:

我正在尝试在 android studio 中创建一个原始的“获取当前位置应用程序”。

按下主页上的按钮后,我希望当前的纬度和经度显示在吐司中。出于某种原因,它们都一直显示为 0.0。

我一直在调试调试器,发现网络提供程序不可用。我不知道这是否是由于在 android studio 上使用了模拟器。

如果有人能告诉我问题出在哪里/如何解决,那就太棒了。

这是我的 MainActivity

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnShowLocation;

// GPSTracker class
GPSTracker gps;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnShowLocation = (Button) findViewById(R.id.show_location);

    // show location button click event
    btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // create class object
            gps = new GPSTracker(MainActivity.this);

            // check if GPS enabled
            if(gps.canGetLocation()){

                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();

                // \n is for new line
                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            }else{
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                gps.showSettingsAlert();
            }

        }
    });
}

}

这是我的 GPSTracker 类

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;


public class GPSTracker extends Service implements LocationListener {


private final Context mContext;

//flag for gps status
boolean isGPSEnabled = false;

//flag for network status
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location;
double latitude;
double longitude;

//The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //ten meters

//The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; //1 minute

//Declaring location manager
LocationManager locationManager;

public GPSTracker(Context context) {

    this.mContext = context;
    getLocation();

}


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

        //getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        //getting Network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            //no network provider is available
        } else {
            this.canGetLocation = true;

            //First get location from provider
            if (isGPSEnabled) {


                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED &&
                        ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    showSettingsAlert();
                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    Toast.makeText(this, location.toString(), Toast.LENGTH_SHORT).show();
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }

            }
        }

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

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

/**
 * Function to get latitude
 */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check if best network provider
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // Setting Icon to Dialog

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
           showSettingsAlert();
        }
        locationManager.removeUpdates(GPSTracker.this);
    }
}



}

如果需要,还有我的 androidManifest

<?xml version="1.0" encoding="utf-8"?>

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />

【问题讨论】:

  • 而不是 isProviderEnabled(),你用 getBestProvider() 试过了吗?
  • 我试过了。我真的不知道如何使用该功能,所以它没有太大帮助。
  • 是的。另外,我认为网络提供商需要粗略的位置访问。无论如何,如果您已经计划了 ACCESS_FINE,最好将其包含在内
  • 我刚刚将 COARSE 位置添加到 Maifest,但没有帮助

标签: android location-services


【解决方案1】:

包含权限&lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/&gt;,然后尝试这样:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
        String permissions[], @NonNull int[] grantResults) {
    switch (requestCode) {

        case Constants.MY_PERMISSIONS_ACCESS_COARSE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                provider = locationManager.getBestProvider(SoulissUtils.getGeoCriteria(), true);
                Log.w(TAG, "MY_PERMISSIONS_ACCESS_COARSE_LOCATION permission granted");

                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    Log.wtf(TAG, "user changed mind?");
                    return;
                }
                locationManager.requestLocationUpdates(provider, Constants.POSITION_UPDATE_INTERVAL,
                        Constants.POSITION_UPDATE_MIN_DIST, this);
                Location location = locationManager.getLastKnownLocation(provider);
                // Initialize the location fields
                if (location != null) {
                    onLocationChanged(location);
                }

            } else {
                // USER denial, log something
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions the app might request
    }
}

然后移动您的以下代码:

          if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    Toast.makeText(this, location.toString(), Toast.LENGTH_SHORT).show();
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }

覆盖onLocationChanged()方法

【讨论】:

  • 我应该把 onRequestPermissionResult() 放在哪里?
  • 在你的服务中,我猜。这个想法是:请求许可,何时/如果被授予(onRequestPermissionResult()),初始化 bestProvider 并询问位置更新。然后,在 onLocationChanged() 中,做这项工作
  • 约束根本不为我编译
  • 是的,这些是最终的静态字符串和 int 你可以决定。我可以硬连线,但可读性会降低
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
相关资源
最近更新 更多