我正在开发一个Location-App,当用户按下button时,该应用应该开始基于经度和纬度来跟踪一些统计数据.所有这些东西都可以很好地工作,但是当涉及到锁定屏幕或将应用程序置于后台时,该服务将不再起作用!
我已经阅读了很多有关后台服务和广播接收器的信息,但是我不知道如何在服务中实现Google Api位置监听器以及在MainActivity中在何处实现此类.谁能用简短的代码示例告诉我如何实现这样的服务或说明链接的链接?
解决方法:
使用保险丝定位服务并每次保存更新的位置
public class LocationNotifyService extends Service implements LocationListener, Googleapiclient.ConnectionCallbacks, Googleapiclient.OnConnectionFailedListener { LocationRequest mLocationRequest; Googleapiclient mGoogleapiclient; public static Location mCurrentLocation; ............................. @OverrIDe public voID onCreate() { //show error dialog if GoolglePlayServices not available if (isGooglePlayServicesAvailable()) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(BACKGROUND_INTERVAL); mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //mLocationRequest.setSmallestdisplacement(10.0f); /* min dist for location change, here it is 10 meter */ mGoogleapiclient = new Googleapiclient.Builder(this) .addAPI(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleapiclient.connect(); } } @OverrIDe public int onStartCommand(Intent intent, int flags, int startID) { return super.onStartCommand(intent, flags, startID); } //Check Google play is available or not private boolean isGooglePlayServicesAvailable() { int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); return ConnectionResult.SUCCESS == status; } @OverrIDe public voID onConnected(Bundle bundle) { startLocationUpdates(); } protected voID startLocationUpdates() { try { PendingResult<Status> pendingResult = LocationServices.FusedLocationAPI.requestLocationUpdates( mGoogleapiclient, mLocationRequest, this); } catch (IllegalStateException e) {} } @OverrIDe public voID onLocationChanged(Location location) { //Save your location } ............................}
您可以在LocationChanged()上获取当前位置
有关更多详细信息,请检查http://javapapers.com/android/android-location-fused-provider/或遵循官方指南https://developer.android.com/training/location/index.html
总结以上是内存溢出为你收集整理的Android定位服务无法在后台运行全部内容,希望文章能够帮你解决Android定位服务无法在后台运行所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)