I'm writing a code to save a bitmap from the app's screen at a specific moment.
I'm doing this by listening to onDraw()
events for some component and checking if a set of conditions is true
@Override
public void onDraw() {
if (checkConditions()) {
Canvas canv = new Canvas(tmpBitmap);
canvasView.draw(canv);
saveBitmapToImage(tmpBitmap, Bitmap.CompressFormat.JPEG);
this.lastDraw = System.currentTimeMillis();
AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
viewKonfetti.getViewTreeObserver().removeOnDrawListener(listener);
});
}
}
But sometimes I'm getting an exception when removing the listener
Fatal Exception: java.lang.IllegalStateException: Cannot call removeOnDrawListener inside of onDraw
at android.view.ViewTreeObserver.removeOnDrawListener(ViewTreeObserver.java:736)
at com.tomatedigital.lottogram.dialogs.ShuffleWinnerDialog$Shuffler$2.lambda$onParticleSystemEnded$1(ShuffleWinnerDialog.java:235)
at com.tomatedigital.lottogram.dialogs.-$$Lambda$ShuffleWinnerDialog$Shuffler$2$vCYJiRVhO65xXIsicqZHHpw_34A.run(-.java:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
This doesn't happen always, it happens sometimes and in production (on many different android devices). BUT WHY?
I'm even using a new thread to remove the listener...
I tested, and even removing the new thread does not solve the issue: this error doesn't occur 100% of the times, just sometimes.
What is the explanation? how to solve it?