Не получать обратные вызовы CountDownTimer в службе

У меня есть служба Bound, которая собирает местоположения в течение 3 минут каждые 15 минут. Я запускаю CountDownTimer, как только служба подключена в onServiceConnected из ServiceConnection.
Я получаю все обратные вызовы таймера (onFinish) (onTick) точно, насколько видна активность, которая bindService.
Когда устройство заблокировано, я не получаю никаких обновлений от таймера.

MyLocationService

public class MyLocationService extends Service implements MyTimerListener{

    private IBinder mBinder = new MyLocationBinder(); 

    public void onCreate() {
        locationManager = new MyLocationManager(this);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    public class MyLocationBinder extends Binder
    {
        public MyLocationService getService()
        {
            return MyLocationService.this;
        }
    }

    public void startFetchingLocations()
    {
        if(locationManager != null){
            locationManager.startFetchingLocations();
            if(publishPeriodCountDownTimer != null) {
                publishPeriodCountDownTimer.cancel();
                publishPeriodCountDownTimer = null;
            }
            publishPeriodCountDownTimer = new MyCountTimer(gpsPublishPeriod * 60 * 1000, 1000, MyLocationService.this);
            publishPeriodCountDownTimer.start();    
        }
    }


    @Override
    public void onTimeFinished() {
        //Start fetching locations
        locationManager.startFetchingLocations(); //Start 3 min CountdownTimer
    }


    @Override
    public void onTick() {

    }

    public void onAllLocationsRecieved(ArrayList<Location> locations)
    {
        //Do stuff on Locations

        locationManager.stopFetchingGPS(); //Stops 3 min countdownTimer
    }
}

Моя активность

public class MyActivity
    {

            @Override
            protected void onStart() {
                super.onStart();
                btnStop.setVisibility(View.VISIBLE);
                MyNoificationManager.cancelAllNotifications();

                if (!isLocationServiceBound) {
                    Intent locServiceIntent = new Intent(this, MyLocationService.class);    
                    bindService(locServiceIntent, locationServiceConnection, Context.BIND_AUTO_CREATE);
                }
        }

        private ServiceConnection locationServiceConnection = new ServiceConnection(){

            @Override
            public void onServiceDisconnected(ComponentName name) {
                isLocationServiceBound = false;

            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                MyLocationBinder locationBinder = (MyLocationBinder) service;
                locationService = locationBinder.getService();
                isLocationServiceBound = true;
                locationService.startFetchingLocations();
            }
        };
    }

Он работает, как и ожидалось, когда активность видна. Таймер не обеспечивает никаких обратных вызовов onTick() или onTimeFinished(), когда устройство заблокировано.
В чем может быть проблема?


person akashsr    schedule 14.11.2014    source источник


Ответы (1)


CountDownTimer не будет работать, когда телефон переходит в спящий режим. Это сделано специально для экономии заряда батареи.

В качестве альтернативы вы можете использовать android.app.AlarmManager вместо этого для достижения своей цели. Ниже приведен пример кода, как это сделать. Установите будильник, как показано ниже

   AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
   Intent intent = new Intent(this, MyLocationService.class);
   intent.putExtra("need_to_fetch_loc", true);
   PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
   alarmManager.set(AlarmManager.RTC_WAKEUP, gpsPublishPeriod * 60 * 1000, alarmIntent);

Добавьте следующий метод в свой класс MyLocationService.

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {

     if(locationManager!= null && intent.getBooleanExtra("need_to_fetch_loc", false))
     {
         locationManager.startFetchingLocations();
     }

     return super.onStartCommand(intent, flags, startId);
 }
person iCoder    schedule 10.12.2014