我正在尝试创建一个即使应用程序不在前台也能保持运行的服务。当它处于前台时,一切正常,但是从其切换后,onLocationChanged
每隔10分钟(而不是处于前台时的5秒)被调用一次。
目标是即使应用程序每隔5秒钟在后台运行一次,也要继续扫描位置并发送更新以进行处理(只要UI应用程序没有完全关闭,我希望该服务保持运行)。
我尝试遵循网上的许多指南和帖子,但没有一个帮助解决这个问题。过去,它在android 6.0上可以正常工作,但我升级到8.0后就停止了工作。
这是我正在使用的代码:
public class MainActivity extends AppCompatActivity {
private Intent _scanServiceIntent;
@Override
public void onStart()
{
super.onStart();
_scanServiceIntent = new Intent(this,ScanService.class);
bindService(_scanServiceIntent, m_serviceConnection, BIND_AUTO_CREATE);
}
private ServiceConnection m_serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
_scanService = ((ScanService.ScanServiceBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
Log.v("lsx", "onServiceDisconnected");
_scanService = null;
}
};
}
This is the ScanService class:
public class ScanService extends Service {
private LocationListener _locListener;
private LocationManager _locManager;
private static final String TAG = "locationtrigger";
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "onBind");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "ScanServiceonStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
Log.v(TAG, "ScanServiceonCreate - start");
List<UserLocationManager> locationsManagers = GetLocationsManagers();
_locListener = new MyLocationListener(locationsManagers);
_locManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
_locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, _locListener);
Log.v(TAG, "ScanServiceonCreate - end");
}
@Override
public void onDestroy() {
_locManager.removeUpdates(_locListener);
}
public List<UserLocationManager> GetLocationsManagers(){
// returning some managers
}
public class ScanServiceBinder extends Binder {
public ScanService getService() {
Log.v(TAG, "ScanServiceBinder.getService");
return ScanService.this;
}
}
class MyLocationListener implements LocationListener {
private List<UserLocationManager> _locationManagers;
public MyLocationListener(List<UserLocationManager> locationManagers)
{
_locationManagers = locationManagers;
}
@Override
public void onLocationChanged(Location location)
{
if (location != null)
{
// call managers
}
}
}
}