我正在尝试在我的Android应用中模拟GPS位置。
我做:
ALLOW_MOCK_LOCATIONS
,ACCESS_MOCK_LOCATION
,ACCESS_COARSE_LOCATION
,ACCESS_FINE_LOCATION
我的接收器类注册位置更新,如下所示:
private void registerLocationListener(){
if(isStarted&&googleApiClient.isConnected()) {
LocationRequest request = new LocationRequest()
.setInterval(1000)
.setSmallestDisplacement(0.5f)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, request, this);
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
我有另一个类,它共享相同的GoogleApiClient
,看起来像这样:
public class LocationMocker{
private final GoogleApiClient googleApiClient;
public LocationMocker(GoogleApiClient apiClient){
this.googleApiClient = apiClient;
}
private void start(){
LocationServices.FusedLocationApi.setMockMode(googleApiClient, true).setResultCallback(new ResultCallbacks<Status>() {
@Override
public void onSuccess(@NonNull Status status) {
Log.e(TAG,"SUCCESS "+status);
new Thread(){
public void run(){
while(!this.isInterrupted()){
Thread.sleep(timeout);
LocationServices.FusedLocationApi.setMockLocation(googleApiClient, generateMockLocation())
.setResultCallback(new ResultCallbacks<Status>() {
@Override
public void onSuccess(@NonNull Status status) {
Log.e(TAG,"NEW MOCKED LOCATION!");
}
@Override
public void onFailure(@NonNull Status status) {
Log.e(TAG,"FAILURE "+status);
}
});
}
}
}.start();
}
@Override
public void onFailure(@NonNull Status status) {
Log.e(TAG,"FAILURE "+status);
}
});
}
}
会发生什么事情,一切都注册正确的方式(我记录所有回调),我也定期看到我的“新的位置!” log,但我的LocationListeners onLocationChanged(位置位置)永远不会被调用。
我也尝试了不同的命令(首先注册locationlistener,首先注册setMockMode,......)。
任何想法我做错了什么? 正如我已经说过的那样:如果我使用真正的GPS,一切正常。
答案 0 :(得分:-1)
为什么使用线程来更新融合位置? 你应该使用:
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
和
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
阅读本文: https://developer.android.com/training/location/receive-location-updates.html