Android background service runs but the timer inside it stops

50 Views Asked by At

Android 14, And Studio Hedgehog, the app records barometric pressure. To keep the app running (or appear to the user to run), the activity starts and binds to a dedicated background service. So far so good, the activity may be shut down by the OS but the service keeps running and when the activity restarts it reconnects to the service and pulls out the data from the service. However, even though the service is running, the countdown timer in the service stops after minutes or hours if the activity is not in focus or device asleep.

Cannot use Job Scheduler because it does jobs when it wants, not on a fixed schedule. CountDownTimer and Handler work similarly with realtime ISRs.

Any suggestions on keeping the service's timer running?

In MainActivity class:

BackgroundService  mService;

protected void onCreate(Bundle savedInstanceState) {
    //benign stuff
    startService(new Intent(this, BackgroundService.class));
    //more stuff
}

private ServiceConnection connection = new ServiceConnection() {  //Bind and unbind to Service
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        BackgroundService.LocalBinder binder = (BackgroundService.LocalBinder) service;
        mService = binder.getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {}
};

//plus usual onStart(), onReset(), ...

In the Service class:

public int TestVar = -1; //[sic]

@Override
public void onCreate() { super.onCreate(); }

@Override
public int onStartCommand(Intent pIntent, int pFlags, int pStartID) {
    Notification  Notification = null;
    NotificationChannel          NotifChannel;
    NotificationCompat.Builder   builder;
    Intent                       IntentTap;
    PendingIntent                PendingTent;
    Date CurTime   = Calendar.getInstance().getTime();
    long StartTime = CurTime.getTime();  //time of first fix (mS from 1970-01-01)

    NotifManager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
    NotifChannel = new NotificationChannel(
        SERVICE_NOTIFICATION_CHANNEL,
        SERVICE_NOTIFICATION_CHANNEL,
        NotificationManager.IMPORTANCE_NONE);
    NotifManager.createNotificationChannel(NotifChannel);
    NotifBuilder = new NotificationCompat.Builder(this, SERVICE_NOTIFICATION_CHANNEL)
        .setSmallIcon(R.drawable.ic_notification)
        .setContextTitle("Bold title")
        .setContentText("Minor text")
        .setOnlyAlertOnce(true)
        .setCategory(Notification.CATEGORY_SERVICE);
    IntentTap = getPackageManager().getLaunchIntentForPackage(getPackageName());  //tap notification to focus activity
    PendingTent = PendingIntent.getActivity(this, 1, IntentTap, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification = NotifBuilder.build();
    startForeground(FOREGROUND_ID, Notification);

    CountDownTimer GpTimer = new CountDownTimer(60*60*24*365*1000, 15000) { //start 15 sec timer
        public void onTick(long mSleft) {  //Every 15 Sec...
            CurTime = Calendar.getInstance().getTime();
            int RunTime = (int)((CurTime.getTime() - StartTime) / 15000);  //actual 15 sec runtimes
            TestVar++;  //increment every 15 seconds ...when it does
            NotifBuilder.setContentText("Realtime: " + RunTime + ", Tics: " + TestVar);
            NotifManager.notify(FOREGROUND_ID, NotifBuilder.build());
        }
        public void onFinish () {}  //year is over, how time flies
    }.start();

    return START_STICKY;
};

//plus usual onTaskRemoved(), onDestroy(), onBind()
1

There are 1 best solutions below

1
TG. Kahsay On

If I am not mistaken, you have to return START_STICKY in your onStartCommand() method. That may be your problem. I am guessing because I don't see enough code in the sample you provided to know otherwise. More reference here