1

I have a service

class BusLocationService : Service()

which is started as START_STICKY and shows a permanent notification.

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    if (intent.action == Constants.ACTION.STARTFOREGROUND_ACTION) {
        registerChannel();
        showNotification();
    }
    return START_STICKY
}

private fun showNotification() {
    val notification = ...
    startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
            notification)
}

It should periodically (once a minute) execute some code but it doesn't. It only does it occasionally (probably while the main activity is visible).

private fun startPermissionActivity() {
    android.os.Handler().postDelayed(
        {
            this@BusLocationService.startPermissionActivity()
        },  60000)
}

Is this postDelayed not reliable? Or the problem is somewhere else? What else could make the service to miss the timer?

Update

When testing in the emulator at home (activity visible), I do see that the code is executed once a minute. The problem happens on the real device (OnePlus 3T) and when the activity is in the background. Sometimes it works (rarely), sometimes (often) it doesn't.

Slawa
  • 1,141
  • 15
  • 21

1 Answers1

0

What ever you wrote will run only once , you have to recall Handler again from Runnable to make it run periodically

try this

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            this@BusLocationService.startPermissionActivity()
             handler.postDelayed(this,60000);
        }
    }, 60000);
Manohar
  • 22,116
  • 9
  • 108
  • 144
  • I should have mentioned that the code with the Handler is inside the function `startPermissionActivity()` which is going to be executed after 60 seconds. So, IMHO, I'm doing the repetitive call to `postDelayed()` already. See also update to the question. – Slawa Sep 17 '18 at 09:01