如何使用FusedLocation API接收每5分钟更新一次的位置



我目前正在开发一个应用程序,它必须每五分钟检查一次用户的位置,并将坐标发送到服务器。我决定在Google Play Services中使用FusedLocation API,而不是普通的旧LocationManager API,主要是因为我注意到了LocationRequest。PRIORITY_BALANCED_POWER_ACCURACY优先级,它声称提供100米的精度水平与合理的电池使用,这正是我所需要的。

在我的例子中,我有一个Activity,它的继承结构是:
public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener

,并实现相关的回调(onConnected, onConnectionFailed, onConnectionSuspended, onLocationChanged)。根据官方文档的建议,我还使用此方法获得GoogleApiClient的实例:

protected synchronized GoogleApiClient buildGoogleApiClient() {
        return new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();

在onConnected中,我使用

开始位置更新
LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient,
                mLocationRequest, this);

…并在onLocationChanged()中捕获更改

然而,我很快发现位置更新似乎在一段时间后停止。也许是因为这个方法与Activity生命周期绑定在一起,我不确定。无论如何,我试图通过创建一个扩展IntentService的内部类并通过AlarmManager启动它来绕过这个问题。所以在onConnected中,我最终这样做了:

AlarmManager alarmMan = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        Intent updateIntent = new Intent(this, LocUpService.class);
        PendingIntent pIntent = PendingIntent.getService(this, 0, updateIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        alarmMan.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0,
                1000 * 60 * 5, pIntent);

LocUpService类是这样的:

public static class LocUpService extends IntentService {
        public LocUpService() {
            super("LocUpService");
        }
        @Override
        protected void onHandleIntent(Intent intent) {
            Coords coords = LocationUpdater.getLastKnownLocation(mApiClient);

        }
    }

LocationUpdater是另一个类,它包含静态方法getLastKnownLocation,它是:

public static Coords getLastKnownLocation(GoogleApiClient apiClient) {
        Coords coords = new Coords();
        Location location = LocationServices.FusedLocationApi
                .getLastLocation(apiClient);
        if (location != null) {
            coords.setLatitude(location.getLatitude());
            coords.setLongitude(location.getLongitude());
            Log.e("lat ", location.getLatitude() + " degrees");
            Log.e("lon ", location.getLongitude() + " degrees");
        }
        return coords;
    }

但惊喜! !我得到"IllegalArgumentException: GoogleApiClient参数是必需的",当我清楚地将引用传递给静态方法时,我再次猜测必须与GoogleApiClient实例与活动的生命周期有关,并且将实例传递到IntentService时出现问题。

所以我在想:我怎样才能每隔五分钟定期更新一次位置而不发疯?我是否扩展一个服务,在该组件上实现所有接口回调,在其中构建GoogleApiClient实例并使其在后台运行?我有一个AlarmManager启动一个服务扩展IntentService每五分钟做的工作,再次有所有相关的回调和GoogleApiClient在IntentService构造?我是否继续做我现在正在做的事情,但将GoogleApiClient构建为一个单例,期望它会有所不同?你会怎么做?

我目前正在开发一个应用程序,它必须每五分钟检查一次用户的位置,并将坐标发送到服务器。我决定在Google Play Services中使用FusedLocation API,而不是普通的旧LocationManager API

我们的应用程序有完全相同的要求,我在几天前实现了它,下面是我如何做到的。

在启动活动或您想要启动的任何地方,使用AlarmManager配置LocationTracker每5分钟运行一次。

private void startLocationTracker() {
    // Configure the LocationTracker's broadcast receiver to run every 5 minutes.
    Intent intent = new Intent(this, LocationTracker.class);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(),
            LocationProvider.FIVE_MINUTES, pendingIntent);
}

LocationTracker.java

public class LocationTracker extends BroadcastReceiver {
    private PowerManager.WakeLock wakeLock;
    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pow = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pow.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wakeLock.acquire();
        Location currentLocation = LocationProvider.getInstance().getCurrentLocation();
        // Send new location to backend. // this will be different for you
        UserService.registerLocation(context, new Handlers.OnRegisterLocationRequestCompleteHandler() {
            @Override
            public void onSuccess() {
                Log.d("success", "UserService.RegisterLocation() succeeded");
                wakeLock.release();
            }
            @Override
            public void onFailure(int statusCode, String errorMessage) {
                Log.d("error", "UserService.RegisterLocation() failed");
                Log.d("error", errorMessage);
                wakeLock.release();
            }
        }, currentLocation);
    }
}

LocationProvider.java

public class LocationProvider {
    private static LocationProvider instance = null;
    private static Context context;
    public static final int ONE_MINUTE = 1000 * 60;
    public static final int FIVE_MINUTES = ONE_MINUTE * 5;
    private static Location currentLocation;
    private LocationProvider() {
    }
    public static LocationProvider getInstance() {
        if (instance == null) {
            instance = new LocationProvider();
        }
        return instance;
    }
    public void configureIfNeeded(Context ctx) {
        if (context == null) {
            context = ctx;
            configureLocationUpdates();
        }
    }
    private void configureLocationUpdates() {
        final LocationRequest locationRequest = createLocationRequest();
        final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
                .addApi(LocationServices.API)
                .build();
        googleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
            @Override
            public void onConnected(Bundle bundle) {
                startLocationUpdates(googleApiClient, locationRequest);
            }
            @Override
            public void onConnectionSuspended(int i) {
            }
        });
        googleApiClient.registerConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {
            }
        });
        googleApiClient.connect();
    }
    private static LocationRequest createLocationRequest() {
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(FIVE_MINUTES);
        return locationRequest;
    }
    private static void startLocationUpdates(GoogleApiClient client, LocationRequest request) {
        LocationServices.FusedLocationApi.requestLocationUpdates(client, request, new com.google.android.gms.location.LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                currentLocation = location;
            }
        });
    }
    public Location getCurrentLocation() {
        return currentLocation;
    }
}

我首先在扩展应用程序的类中创建LocationProvider的实例,在应用程序启动时创建该实例:

MyApp.java

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        LocationProvider locationProvider = LocationProvider.getInstance();
        locationProvider.configureIfNeeded(this);
    }
}

LocationProvider被实例化并配置为位置只更新一次,因为它是一个单例。每隔5分钟,它将更新它的currentLocation值,我们可以通过

从需要的任何地方检索该值。
Location loc = LocationProvider.getInstance().getCurrentLocation();

不需要运行任何类型的后台服务。AlarmManager将每5分钟向LocationTracker.onReceive()广播一次,部分唤醒锁将确保即使设备处于待机状态,代码也将完成运行。这也是节能的。

请注意,您需要以下权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- For keeping the LocationTracker alive while it is doing networking -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

,别忘了登记收信人:

<receiver android:name=".LocationTracker" />

关于你的第一个方法,你正在使用活动请求位置更新,他们不应该停止,除非你在活动的onPause()方法断开位置客户端。所以只要你的活动在后台/前台,你应该继续接收位置更新。但是如果activity被销毁,那么你当然不会得到更新。

检查是否在活动生命周期中断开了位置客户端。

相关内容

  • 没有找到相关文章

最新更新