Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timer Cancellation #6

Open
IRMobydick opened this issue Sep 9, 2023 · 0 comments
Open

Timer Cancellation #6

IRMobydick opened this issue Sep 9, 2023 · 0 comments

Comments

@IRMobydick
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant