Java 无法获取当前位置
我需要获取当前设备位置(lat/lng),但“getCurrentLocation()”始终显示“无提供程序”,因此位置为空。我在onCreate()中调用此方法,并在清单文件中声明了所有权限:Java 无法获取当前位置,java,android,location,Java,Android,Location,我需要获取当前设备位置(lat/lng),但“getCurrentLocation()”始终显示“无提供程序”,因此位置为空。我在onCreate()中调用此方法,并在清单文件中声明了所有权限: <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> 我
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
我怎样才能修好它
我修改了很多类似的问题,但找不到合适的解决方案。
首先考虑使用FooDealPosivices提供程序代替LooCuffor。您可以找到如何使用id的指南
第二,你试图得到“最后一个已知的位置”,但它并不总是在那里。要接收用户位置,您需要订阅LocationManager更新。这是一个如何做到这一点的例子public class GPSTracker extends Service implements LocationListener {
private final Activity mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Activity 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 enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
checkLocationPermission();
if (isNetworkEnabled) {
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.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
checkLocationPermission();
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* 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 GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
//alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("Please enable GPS to get locations.");
// 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();
}
@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;
}
public boolean checkLocationPermission()
{
if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}
else
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDisabledAlertToUser();
}
return true;
}
}
private void showGPSDisabledAlertToUser()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
尝试此代码,无论何时需要获取位置,都可以创建GPS对象并检索lat和long
例如:
在代码中尝试此更改不保证
.getLastKnownLocation()
返回以前存储的位置数据
它可以返回一个null
因此,您必须为需要监听位置更新的情况做好准备。您可以这样向他们注册:
locationManager
.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//here you receive the new location
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}););
您已经评论了有关权限的部分,您是否至少使用设置授予了权限?(Android 5.0及之前版本)何时更新
位置
<代码>公共void onLocation已更改(位置){未实现。我不认为这是使用侦听器仅获取一个位置的最佳解决方案。从您自己的项目中复制粘贴一卡车代码并不是一个好的答案。这根本无法回答问题。我使用完全相同的代码来获取纬度和长度,但您无法回答我?所以我猜您不会“我不理解它……老实说,它比它应该的要长得多。如果你只有GPS,这将不起作用,因为你需要在请求位置更新
和收到的第一个位置之间留出一段时间。此外,你至少应该在某处呼叫停止使用GPS
,因为在你的示例中,GPS保持启用状态。要接收用户,请您需要订阅的LocationManager更新不正确。仅当您需要时updates@TimCastelijns如果您没有收到最后已知的位置,那么订阅是唯一的选择。
GPSTracker gpsTracker = new GPSTracker(activity);
Latitude = gpsTracker.getLatitude();
Longtude = gpsTracker.getLongitude();
provider = locationManager.getBestProvider(c, true);
locationManager
.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//here you receive the new location
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}););