jea*_*rme 6 android android-location samsung-mobile
它适用于除Galaxy Note 2之外的大多数设备.它连接到Google客户端,但无法访问onLocationChanged()
该实现LocationListener
.任何人都知道它是什么原因以及为什么只能在这个设备上?
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
Toast.makeText(getApplicationContext(), String.valueOf(lat) + "/" + String.valueOf(lng), Toast.LENGTH_LONG).show();
serverUrl = "http://(my server)/offers?lat=" + String.valueOf(mLastLocation.getLatitude())
+ "&lng=" + String.valueOf(mLastLocation.getLongitude()) + "&distance=1";
// save
makeTag(serverUrl);
// after getting location data - unregister listener
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mFusedLocationCallback);
new GetBackgroundUpdate().execute();
} else {
// get data from server and update GridView
new GetBackgroundUpdate().execute();
Toast.makeText(getApplicationContext(), R.string.no_location_detected, Toast.LENGTH_LONG).show();
}
/**
Location methods
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback);
}
@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());
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GooglePlayServicesUtil.getErrorDialog()
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(String.valueOf(result.getErrorCode()))
.setCancelable(false)
.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
mResolvingError = true;
}
//new GetBackgroundUpdate().execute();
}
@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();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:从评论中NullPointerException
正在发生的行开始,确保mLastLocation
不为空.
if (mLastLocation != null){
address = server + String.valueOf(mLastLocation.getLatitude()) + "&lng=" + String.valueOf(mLastLocation.getLongitude()) + "&distance=" + distance;
}
Run Code Online (Sandbox Code Playgroud)
另外需要注意的是,mGoogleApiClient
在使用它之前,应始终确保它不是null并且已连接.
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()){
//..... use mGoogleApiClient.....
}
Run Code Online (Sandbox Code Playgroud)
您还应该添加一项检查,以查看Google Play服务是否可用,因为设备上的可用版本有时低于您编译应用的版本.如果是这种情况,您可以显示一个对话框.
以下是检查Google Play服务是否可用的方法.
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,getLastLocation()
返回null的倾向很高,因此如果从第一次调用获得空值,则可以注册位置侦听器getLastLocation()
.
看到这篇文章: LocationClient getLastLocation()返回null
以下是如何注册的指南LocationListener
:
创建一个监听器:
LocationCallback mFusedLocationCallback = new LocationCallback();
Run Code Online (Sandbox Code Playgroud)
班级定义:
private class LocationCallback implements LocationListener {
public LocationCallback() {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
lat = String.valueOf(mLastLocation.getLatitude());
lng = String.valueOf(mLastLocation.getLongitude());
}
};
Run Code Online (Sandbox Code Playgroud)
然后注册LocationListener
:
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(minTime);
mLocationRequest.setFastestInterval(fastestTime);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(distanceThreshold);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback);
Run Code Online (Sandbox Code Playgroud)
编辑:您应该在注册位置回调之前等待API连接,它应该是这样的:
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lng = String.valueOf(mLastLocation.getLongitude());
} else {
Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback);
}
Run Code Online (Sandbox Code Playgroud)
文档:用于requestLocationUpdates ....和LocationRequest.
最后一件事,确保你在application
标签内的AndroidManifest.xml中有这个:
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
392 次 |
最近记录: |