我目前正在开发一款每五分钟检查一次用户位置的应用,并将坐标发送到服务器。我决定使用Google Play服务中的FusedLocation API而不是普通的旧BitManager 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实例涉及Activity的生命周期有关,并且将实例传递给IntentService。
所以我在想:如何每五分钟定期更新一次而不会发疯?我是否扩展服务,在该组件上实现所有接口回调,在那里构建GoogleApiClient实例并使其在后台运行?我是否有一个AlarmManager启动一个服务,每隔五分钟就会扩展一次IntentService来完成工作,再次在IntentService中构建所有相关的回调和GoogleApiClient?我是否一直在做我现在正在做的事情但是将GoogleApiClient构建为单身人士,期待它会有所作为?你会怎么做?
感谢并且抱歉这是如此啰嗦。
答案 0 :(得分:7)
我目前正在开发一款每五分钟检查一次用户位置的应用,并将坐标发送到服务器。我决定使用Google Play服务中的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" />
答案 1 :(得分:0)
关于您使用活动来请求位置更新的第一种方法,除非您在活动的onPause()方法中断开位置客户端,否则它们不应该停止。因此,只要您的活动位于后台/前台,您就应该继续接收位置更新。但是如果活动被破坏,那么你当然不会得到更新。
检查您是否在活动生命周期中断开客户端的位置。