我的任务是从相机获取预览帧,对其进行处理并更新布局中的TextView。我引用的是Google的camera2示例代码,并已设法使用OnImageAvailableListener的OnImageAvailable()
方法获取帧,但无法更新TextView的内容在OnImageAvailable()
定义中(应用程序崩溃)。我是Android编程和Java的新手。获取每帧后更新我的TextView的任何方法。
OnImageAvailable的定义(片段的一部分,而不是CameraActivity,例如Google的示例):
public final ImageReader.OnImageAvailableListener mOnImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] imageBytes = new byte[buffer.remaining()];
buffer.get(imageBytes);
final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
textView.append("a"); // crashes here
} finally {
if (image != null) {
image.close();
}
}
}
};
来自Android Monitor的崩溃日志:
03-19 13:14:12.384 13895-14107/com.example.android.camera2basic E/AndroidRuntime: FATAL EXCEPTION: CameraBackground
Process: com.example.android.camera2basic, PID: 13895
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6462)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:932)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4692)
at android.view.View.invalidateInternal(View.java:11806)
at android.view.View.invalidate(View.java:11770)
at android.view.View.invalidate(View.java:11754)
at android.widget.TextView.checkForRelayout(TextView.java:6867)
at android.widget.TextView.setText(TextView.java:4063)
at android.widget.TextView.setText(TextView.java:3921)
at android.widget.TextView.append(TextView.java:3627)
at android.widget.TextView.append(TextView.java:3617)
at com.example.android.camera2basic.Camera2BasicFragment$6.onImageAvailable(Camera2BasicFragment.java:760)
at android.media.ImageReader$ListenerHandler.handleMessage(ImageReader.java:548)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
最佳答案
您需要将其放在可运行/线程中。我并不是很精通它,但是也许这可能会有所帮助,但是如果没有,我非常肯定它会为解决方案指明正确的方向
public final ImageReader.OnImageAvailableListener mOnImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(final ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] imageBytes = new byte[buffer.remaining()];
buffer.get(imageBytes);
final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
YourClassNameHere.this.runOnUIThread(new Runnable() {
@Override
public void run() {
textView.append("a"); // crashes here
});
} finally {
if (image != null) {
image.close();
}
}
}
}
};
关于java - 在ImageReader的OnImageAvailable中更新MainActivity的TextView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42883971/