Ant*_*427 2 java android android-fusedlocation android-googleapiclient
我目前正在开发一个应用程序,它必须每五分钟检查一次用户的位置并将坐标发送到服务器.我决定使用Google Play服务中的FusedLocation API而不是普通的旧BitManager API,主要是因为我注意到了LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY优先级,声称提供100米精度等级且电池使用合理,这正是我需要.
在我的例子中,我有一个Activity,其继承结构是:
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener
Run Code Online (Sandbox Code Playgroud)
并实现相关的回调(onConnected,onConnectionFailed,onConnectionSuspended,onLocationChanged).根据官方文档的建议,我还使用此方法获取了GoogleApiClient的实例:
protected synchronized GoogleApiClient buildGoogleApiClient() {
return new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
Run Code Online (Sandbox Code Playgroud)
在onConnected中,我使用启动位置更新
LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient,
mLocationRequest, this);
Run Code Online (Sandbox Code Playgroud)
...并捕获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);
Run Code Online (Sandbox Code Playgroud)
LocUpService类如下所示:
public static class LocUpService extends IntentService {
public LocUpService() {
super("LocUpService");
}
@Override
protected void onHandleIntent(Intent intent) {
Coords coords = LocationUpdater.getLastKnownLocation(mApiClient);
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
但是惊喜!! 我得到"IllegalArgumentException:GoogleApiClient参数是必需的",当我清楚地传递对静态方法的引用时,我认为必须与GoogleApiClient实例有关的事件与Activity的生命周期有关,并且将实例传递给IntentService.
所以我在想:如何每五分钟定期更新一次而不会发疯?我是否扩展服务,在该组件上实现所有接口回调,在那里构建GoogleApiClient实例并使其在后台运行?我是否有一个AlarmManager启动一个服务,每隔五分钟就会扩展一次IntentService来完成工作,再次在IntentService中构建所有相关的回调和GoogleApiClient?我是否一直在做我现在正在做的事情但是将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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我首先在扩展应用程序的类中创建LocationProvider的实例,在启动应用程序时创建实例:
MyApp.java
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
LocationProvider locationProvider = LocationProvider.getInstance();
locationProvider.configureIfNeeded(this);
}
}
Run Code Online (Sandbox Code Playgroud)
LocationProvider实例化并配置为位置更新一次,因为它是一个单例.每隔5分钟,它将更新其currentLocation
值,我们可以从我们需要的任何地方检索它
Location loc = LocationProvider.getInstance().getCurrentLocation();
Run Code Online (Sandbox Code Playgroud)
不需要运行任何类型的后台服务.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" />
Run Code Online (Sandbox Code Playgroud)
并且不要忘记注册接收者:
<receiver android:name=".LocationTracker" />
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2971 次 |
最近记录: |