我是Android的新手,它根据位置创建了一个简单的应用程序。 当用户在不打开位置的情况下打开应用程序时,它将直接进入设置,如果打开则从那里进行设置, 太晚获取lat和lang值。
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.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
public class GPSTracking extends Service implements LocationListener
{
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
Location mLocation;
private double lat;
private double lng;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
private static final long MIN_TIME_BW_UPDATE = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracking(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled =
locationManager.isProviderEnabled(lo
cationManager.GPS_PROVIDER);
isNetworkEnabled =
locationManager.isProviderEnabled(locat
ionManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
//no network or gps
}
else
{
setCanGetLocation(true);
if (isNetworkEnabled)
{
if(locationManager!=null)
{
mLocation =
locationManager.getLastKnownLocation
(LocationManager.NETWORK_PROVIDER);
if(mLocation!=null)
{
setLat(mLocation.getLatitude());
setLng(mLocation.getLongitude());
}
}
}
if (isGPSEnabled)
{
if (mLocation == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
if (locationManager != null)
{
mLocation = locationManager
.getLastKnownLocation(LocationManager
.GPS_PROVIDER);
if (mLocation != null)
{
setLat(mLocation.getLatitude());
setLng(mLocation.getLongitude());
}
}
}
}
}
}
catch (Exception e)
{
//Exception
}
return mLocation;
}
public void showAlertDialog()
{
AlertDialog.Builder alertDialog = new
AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want go to
settings menu?");
alertDialog.setPositiveButton("Settings", new
DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@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)
{
//Toast.makeText(mContext, "Please turn on the location",
// Toast.LENGTH_SHORT).show();
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng; //this is the lat
}
public boolean isCanGetLocation() {
return canGetLocation;
}
public void setCanGetLocation(boolean canGetLocation)
{
this.canGetLocation = canGetLocation; //this is canGetLocation which will do the following thing.
}
}`*
答案 0 :(得分:0)
据我所知,这取决于电话,打开或关闭wifi,准确性
还有三种类型的位置:
GPS_PROVIDER
NETWORK_PROVIDER
PASSIVE_PROVIDER
所以,根据我的经验,我知道如果您使用:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, new MyLocationListener());
您将获得高达14+小数位的精度。
但是,如果您像这样使用它们的融合:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, my_google_listener);
您将获得高达6到7个小数位的精度。尝试一下 !!!参考
但是请注意,GPS Provider需要花费一些时间来获取位置,而Google定位要快得多,因为它可以将API调用中的数据获取到其Google服务器数据库中。
GPS脱机工作,而Google提供者通过移动或wifi数据获取位置。
答案 1 :(得分:0)
您可以尝试使用google api客户端获取用户位置,请尝试
它将打开位置,而无需像其他Google应用一样浏览设置
public class ActivitySignUp extends BaseActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS = 0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_activity);
setUpGClient();
}
//set user api client for access location
private synchronized void setUpGClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
mylocation = location;
if (mylocation != null) {
Double latitude = mylocation.getLatitude();
Double longitude = mylocation.getLongitude();
if (latitude != 0 && longitude != 0) {
Log.e("Lat Long", "Lat " + latitude + " && Long " + longitude);
//here is your lat long
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
//Or Do whatever you want with your location
}
}
@Override
public void onConnected(Bundle bundle) {
checkPermissions();
}
@Override
public void onConnectionSuspended(int i) {
//Do whatever you need
//You can display a message here
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//You can display a message here
}
private void getMyLocation() {
if (googleApiClient != null) {
if (googleApiClient.isConnected()) {
int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, ActivitySignUp.this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied.
// You can initialize location requests here.
int permissionLocation = ContextCompat
.checkSelfPermission(ActivitySignUp.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied.
// But could be fixed by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// Ask to turn on GPS automatically
status.startResolutionForResult(ActivitySignUp.this,
REQUEST_CHECK_SETTINGS_GPS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS_GPS:
switch (resultCode) {
case Activity.RESULT_OK:
getMyLocation();
break;
case Activity.RESULT_CANCELED:
finish();
break;
}
break;
}
}
private void checkPermissions() {
int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
}
} else {
getMyLocation();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permissionLocation = ContextCompat.checkSelfPermission(ActivitySignUp.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
让我知道是否有帮助