【发布时间】:2018-06-24 05:53:51
【问题描述】:
在 Android O (8.0.0+) (API 26+) 中,如何在应用处于后台或终止时获取位置服务更新。在“Strava”Android 应用程序(Play Store 上可用)中,定位服务在应用程序处于后台或终止时正常运行。我需要在我的应用程序中构建相同的功能。 每当我开始使用服务时
startService(new Intent(this, GpsServices.class));
然后当应用处于空闲模式(应用在后台或被杀死)时,在 10 秒后调用 onDestroy 方法。下面是我的代码。
public class GpsServices extends Service implements LocationListener, Listener {
@Override
public void onCreate() {
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mLocationManager != null) {
mLocationManager.addGpsStatusListener(this);
}
if (mLocationManager != null) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
500,
0,
this);
}
}
public void onLocationChanged(Location location) {
System.out.println("location = [" + location + "]");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
/* Remove the locationlistener updates when Services is stopped */
@Override
public void onDestroy() {
try {
mLocationManager.removeUpdates(this);
mLocationManager.removeGpsStatusListener(this);
stopForeground(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
任何帮助将不胜感激。
【问题讨论】:
-
你应该阅读如何在后台处理位置developer.android.com/about/versions/oreo/…
-
如果您能提供解决方案,那将很有帮助。我已经阅读了您提供的链接。但是不推荐使用 GeofencingApi 和 FusedLocationProviderApi 接口。
-
请阅读链接,使用这些与实际问题无关
标签: android background geolocation android-service android-8.0-oreo