我的应用程序中启用了硬件加速,但由于我在笔划上限和其他方面遇到了问题,因此我为我的一个视图禁用了它。
现在我在 Google Play 崩溃错误控制台中获得了以下堆栈跟踪:
java.lang.UnsupportedOperationException
at android.view.GLES20Canvas.clipPath(GLES20Canvas.java:287)
at com.myapp.MyCustomView.onDraw(SourceFile:288)
at android.view.View.draw(View.java:9310)
at android.view.View.getDisplayList(View.java:8773)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:2298)
...
at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:609)
at android.view.ViewRoot.draw(ViewRoot.java:1634)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1450)
at android.view.ViewRoot.handleMessage(ViewRoot.java:2094)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4123)
...
我已经在AndroidManifest.xml中指定了android:hardwareAccelerated="true"
。但我在自定义视图的构造函数中特别禁用了硬件加速:
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// ... code omitted
// disable acceleration because Paint.setStrokeCap(Cap.ROUND) is not working otherwise
Compatibility.disableHardwareAcceleration(this);
}
兼容性如下:
public class Compatibility {
// View.setLayerType() was introduced in Honeycomb
private static Method setLayerTypeMethod = getMethod(View.class, "setLayerType", int.class,
Paint.class);
private static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
try {
return clazz.getMethod(name, parameterTypes);
}
catch (NoSuchMethodException e) {
return null;
}
}
private Compatibility() {
}
public static void disableHardwareAcceleration(View view) {
try {
if (setLayerTypeMethod != null) {
int layerType = 1; // View.LAYER_TYPE_SOFTWARE
setLayerTypeMethod.invoke(view, layerType, null);
}
}
catch (Exception ignored) {
}
}
}
不幸的是,崩溃错误控制台不会显示有关 Android 操作系统版本或设备的信息。
知道会发生什么吗?
存在一个已知问题,即即使设置了LAYER_TYPE_SOFTWARE,仍使用硬件加速绘制视图。详情请见此处
作为解决方法,您可以做两件事
- 使用 Canvas.isHardwareAccelerated() 跳过有问题的代码。
- 将有问题的内容绘制到位图中,并使用canvas.drawBitmap()将其绘制到硬件加速视图上。