【发布时间】:2017-12-01 03:28:14
【问题描述】:
编辑:我已将工作代码放在这里。每个人都可以复制粘贴来运行代码。现在有 4 种获取 Location 的方法,但结果为 null。
我已经尝试了超过 5 种有关位置的代码,但大多数情况下,有 3 种方法可以使用 Android 访问位置数据。所有这些代码都返回 null。设备位置(GPS 和 WIFI)已打开。已在 AndroidManifest.xml 上设置权限。我在真机和 AVD 模拟器上试过,结果一样:return null。有人可以告诉我代码有什么问题吗?都是工作代码(在我的电脑中)。
1。 LocationManager & LocationListener
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@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) {}
};
String coarse = "android.permission.ACCESS_COARSE_LOCATION";
String fine = "android.permission.ACCESS_FINE_LOCATION";
if (ContextCompat.checkSelfPermission(this, coarse) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{coarse}, 101);
}
if (ContextCompat.checkSelfPermission(this, fine) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{fine}, 102);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, (android.location.LocationListener) locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
System.out.println("LATITUDE: " + location.getLatitude());
System.out.println("LONGITUDE: " + location.getLongitude());
} else {
System.out.println("LOCATION IS NULL");
}
}
}
2。 FusedLocationProviderClient
public class MainActivity extends AppCompatActivity {
private LocationRequest mLocationRequest;
private FusedLocationProviderClient locationClient;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startLocationUpdates();
}
// Trigger new location updates at interval
protected void startLocationUpdates() {
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
String coarse = "android.permission.ACCESS_COARSE_LOCATION";
String fine = "android.permission.ACCESS_FINE_LOCATION";
if (ContextCompat.checkSelfPermission(this, coarse) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{coarse}, 101);
}
if (ContextCompat.checkSelfPermission(this, fine) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{fine}, 102);
}
LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
// do work here
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
}
public void onLocationChanged(Location location) {
// New location has now been determined
String msg = "Updated Location: " + location.getLatitude() + "," + location.getLongitude();
System.out.println(msg);
}
}
3。 FusedLocationApi
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
protected static final String TAG = "main-activity";
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buildGoogleApiClient();
}
/**
* Builds a GoogleApiClient. Uses {@code #addApi} to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
// Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
String coarse = "android.permission.ACCESS_COARSE_LOCATION";
String fine = "android.permission.ACCESS_FINE_LOCATION";
if (ContextCompat.checkSelfPermission(this, coarse) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{coarse}, 101);
}
if (ContextCompat.checkSelfPermission(this, fine) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{fine}, 102);
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
System.out.println("LATITUDE: " + mLastLocation.getLatitude());
System.out.println("LONGITUDE: " + mLastLocation.getLongitude());
// It is possible that the user presses the button to get the address before the
// GoogleApiClient object successfully connects. In such a case, mAddressRequested
// is set to true, but no attempt is made to fetch the address (see
// fetchAddressButtonHandler()) . Instead, we start the intent service here if the
// user has requested an address, since we now have a connection to GoogleApiClient.
} else {
System.out.println("LOCATION IS NULL");
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
}
4 SmartLocation 库:编译 'io.nlopez.smartlocation:library:3.2.9'
public class Location1Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("ON LOCATION1ACTIVITY");
SmartLocation.with(this).location()
.oneFix()
.start(new OnLocationUpdatedListener() {
@Override
public void onLocationUpdated(Location location) {
if (location == null) {
System.out.println("LOCATION IS NULL");
} else {
System.out.println("LATITUDE: " + location.getLatitude());
System.out.println("LONGITUDE: " + location.getLongitude());
}
}
});
}
}
【问题讨论】:
-
不行,Hitesh。我的代码:
SmartLocation.with(this).location() .oneFix() .start(new OnLocationUpdatedListener() { @Override public void onLocationUpdated(Location l) { if (l == null) { Sout("LOC IS NULL"); } else { Sout("LAT: " + l.getLatitude()); Sout("LNG: " + l.getLongitude()); } } }); -
你能达到你想要的吗?
-
不工作。我使用了来自 github 的适当代码。我设置了 System.out.println,但 logcat 上没有打印任何内容。
-
确保您的应用程序确实具有 ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION(两者)以获得准确的结果。不要忘记在运行时为 Android 6.0 及更高版本请求权限。