Canvas restore() 在极少数情况下导致下溢异常

Tre*_*vor 6 android underflow android-canvas

通过 ACRA,我收到了少量来自软件 alpha 版本的报告,这些报告显示在对Canvas.restore(). 例外是java.lang.IllegalStateException: Underflow in restore

我很清楚,如果restore()调用次数多于save()调用次数,则会发生此异常。但是,通过非常仔细的代码检查,我绝对确定所有对canvas.save()和 的调用canvas.restore()都是平衡的。也就是说,所有对 的调用canvas.save()肯定会在稍后阶段通过对 的调用进行平衡canvas.restore()。我还可以确认没有条件、异常或方法的早期返回可能导致丢失canvas.save()导致堆栈下溢。

此外,这个问题似乎是一种罕见的边缘情况,它导致异常在每秒渲染多次的图形代码中只发生几次。

发生这种情况的代码结构是:

protected void onDraw(Canvas canvas) {
    ...
    someMethod(canvas);
    ...
}

void someMethod(Canvas canvas)
{
    ....
    canvas.save();
    ....
    someOtherMethod(Canvas canvas);
    ....
    canvas.restore();  
    ....
}

void someOtherMethod(Canvas canvas)
{

    ....
    canvas.save();
    ....
    for ( ... ) {

        ....
        canvas.save();
        ...
        canvas.restore();
        ...
    }
    ....
    canvas.restore();   // *** exception here ***   
    ....
}
Run Code Online (Sandbox Code Playgroud)

有些地方在循环中使用save()/ restore(),但调用又是平衡的。

这些报告来自运行 4.3 和 4.4.2 的设备。

我试图在谷歌上搜索这个问题,我能找到的唯一有趣的 QA 来自一个在他的代码中显然有不平衡的 save()/restore() 调用的人;就我而言,这绝对不是问题。

这发生在自定义 View 子类onDraw(Canvas canvas)方法的调用堆栈中,所有发生在 UI 线程上。我没有其他线程触及该Canvas对象。

getSaveCount()在调用负责异常的特定 restore() 之前,我可能会通过调用来检查堆栈,但这实际上只是将 Elastoplast 粘在问题上。我宁愿了解导致下溢的边缘情况到底是什么,但这让我感到困惑。

是否存在任何已知问题?Canvas当 UI 线程在 aViewonDraw()调用上下文中时,任何类型的系统配置更改是否有可能影响这一点?Canvas堆栈大小是否有任何已知限制?是否有任何已知的操作系统图形调用会滥用画布堆栈?

Tre*_*vor 2

这不是解释根本原因的答案,遗憾的是我仍然不知道原因。我在这里介绍的是让我能够应对这个问题的解决方案。

很简单,整个渲染过程就被一个try/包围起来catch,如下:

        try {
            ...
            // calls go within here to render to the canvas many times
            ...

        }
        catch (java.lang.IllegalStateException exception) {
            // Attempt to catch rare mysterious Canvas stack underflow events that have been reported in
            // ACRA, but simply should not be happening because Canvas save()/restore() calls are definitely
            // balanced. The exception is: java.lang.IllegalStateException: Underflow in restore
            // See: stackoverflow.com/questions/23893813/
            if (exception.getMessage() != null && (//
                    exception.getMessage().contains("Underflow in restore") || //
                    exception.getCause().getMessage().contains("Underflow in restore"))) { //
                DebugLog.getInstance().e("Caught a Canvas stack underflow! (java.lang.IllegalStateException: Underflow in restore)");
            }
            else {
                // It wasn't a Canvas underflow, so re-throw.
                throw exception;
            }
        }
Run Code Online (Sandbox Code Playgroud)

请注意,这DebugLog.getInstance().e是我自己的 SD 卡调试记录器类,我在此不详细说明;您可以将该调用替换为您想要记录异常的任何内容。

此后,一些用户的设备向我发送了与完全不同的问题相关的 ACRA 报告,我注意到其中一些报告包含附加日志,显示这些Canvas异常已被捕获。这似乎来自三星 Galaxy 设备。从日志来看,设备可能抛出了两到三次此异常,但随后用户已经能够继续正常使用该应用程序。因此,捕获并本质上掩盖此异常似乎不会产生长期的负面影响。