Skip to content

Timer Cancellation #6

@IRMobydick

Description

@IRMobydick

In the onVisibilityChanged method, we have:

@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
    super.onVisibilityChanged(changedView, visibility);

    if (visibility == View.INVISIBLE) {
        timer.cancel();
    } else {
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        NSidedProgressBar.this.invalidate();
                    }
                });
            }
        }, 0, 1000 / refreshRate);
    }
}

When the visibility changes back to VISIBLE, you create a new Timer without canceling the existing one if it's not null. This can result in multiple timers running simultaneously, causing unexpected behavior and even performance issues. You should either reuse the existing timer or cancel it before creating a new one.

@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
    super.onVisibilityChanged(changedView, visibility);

    if (timer != null) {
        timer.cancel();
        timer = null; // Ensure the timer is set to null after cancellation.
    }

    if (visibility == View.VISIBLE) {
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (context instanceof Activity) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            NSidedProgressBar.this.invalidate();
                        }
                    });
                }
            }
        }, 0, 1000 / refreshRate);
}

}

P.s: Casting the context object to an Activity can be problematic, As mentioned in issues earlier by another user. A safer way to perform UI-related tasks is to use a Handler or View.post instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions