无法使用通用代码获取 GPS 位置
Posted
技术标签:
【中文标题】无法使用通用代码获取 GPS 位置【英文标题】:Unable to get GPS Location with Common Code 【发布时间】:2015-08-01 05:05:48 【问题描述】:我有获取位置的代码,我认为它必须有效,但它根本不起作用:
清单:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Java:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
new MyLocationListener()
);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
System.out.println("location: " + location);
location 打印 null 并且侦听器根本不会被调用。任何人都可以建议有什么问题吗?如果我打开 Google 地图,它仍然可以返回我的位置。
注意:我正在使用我的设备进行测试
【问题讨论】:
这样做只是检查这个链接它会帮助你***.com/questions/1513485/… 什么是mLLocationManager?因为在你的代码中你使用 locationManager 来注册更新,所以你应该使用 locationManager 来代替 @Gautam 抱歉忘记编辑那个。 【参考方案1】:添加此 Gps 跟踪器类
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;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// 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 * 30 * 1; // 30 seconds
// Declaring a Location Manager
protected 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 enabled
else
this.canGetLocation = true;
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)
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("GPS is not enabled. Do you want to go to settings menu?");
// 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)
if(location!=null)
try
latitude=location.getLatitude();
longitude=location.getLongitude();
catch (Exception e)
e.printStackTrace();
@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;
并从以下代码中获取 Lat & Long 值,
double lat=gpstracker.getLatitude();
double long=gpstracker.getLongitude();
简单教程,
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
【讨论】:
问题是,它只能获取网络位置,而不是我想要的GPS。【参考方案2】:在您的实用程序包中或您可以使用以下代码的任何地方创建类SingleShotLocationProvider
。
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
public class SingleShotLocationProvider
public interface LocationCallback
void onNewLocationAvailable(Location location);
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback)
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (Utility.checkAndRequestPermissionsForGPS(context))
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
Toast.makeText(context, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled)
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener()
@Override
public void onLocationChanged(Location location)
callback.onNewLocationAvailable(location);
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public void onProviderEnabled(String provider)
@Override
public void onProviderDisabled(String provider)
, null);
else
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled)
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, new LocationListener()
@Override
public void onLocationChanged(Location location)
callback.onNewLocationAvailable(location);
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public void onProviderEnabled(String provider)
@Override
public void onProviderDisabled(String provider)
, null);
现在在你的 Activity 中像这样导入它
import com.yourdomain.utils.SingleShotLocationProvider;
现在你可以像下面这样使用它 this
是对你的活动的引用
SingleShotLocationProvider.requestSingleUpdate(this,
new SingleShotLocationProvider.LocationCallback()
@Override
public void onNewLocationAvailable(Location location)
if (location != null)
double latitude = location.getLatitude();
double longitude = location.getLongitude();
);
您将在第一次尝试时收到位置,只需确保 GPS 已打开并设置为高精度。在清单中您已授予必要的权限,如下所示 -
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
【讨论】:
【参考方案3】:试试这个代码。我在这里使用 GPS 来获取纬度和经度。
Criteria criteria = new Criteria();
// Getting the name of the best provider
provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
location = locationManager.getLastKnownLocation(provider);
if (location != null)
System.out.println("Get Last LOcation" + location.getLatitude()
+ location.getLongitude());
loc.setLatitude(location.getLatitude());
loc.setLongitude(location.getLongitude());
locationListener = new LocationListener()
@Override
public void onStatusChanged(String provider, int status,
Bundle extras)
// TODO Auto-generated method stub
@Override
public void onProviderEnabled(String provider)
// TODO Auto-generated method stub
@Override
public void onProviderDisabled(String provider)
// TODO Auto-generated method stub
@Override
public void onLocationChanged(Location location)
// TODO Auto-generated method stub
if (location.getAccuracy() < 50)
locationManager.removeUpdates(locationListener);
;
locationManager.requestLocationUpdates(provider,
INTERVAL_TIME_SECONDS, MIN_DISTANCE_METERS,
locationListener);
【讨论】:
以上是关于无法使用通用代码获取 GPS 位置的主要内容,如果未能解决你的问题,请参考以下文章