2 starbenx starbenx 于 2016.02.29 15:14 提问

从SurfaceView类中向主UI发送消息

我想在子线程的子类中向UI线程发送消息更新界面.
首先成功了一个小例子:
mainActivity{
Handler h = new
@Override
public void handleMessage(Message msg){
一堆更新UI操作...
};

Runnable r = new Runnable() {
@Override
public void run() {
subclass s = new subclass(h);
subclass.do();
}
};

protected void onCreate(Bundle savedInstanceState).......
}

public class subclass{
public Handler mh;
public subclass (Handler h){
mh = h;
}
public void do(){
Message msg = mh.obtainMessage();
msg.sendToTarget();
}
}
但是我将子类subclass换成SurfaceView,构造器为
public SurfaceView(Context context, Handler h) {mh = h}
然后在CALLBACK 的surfaceCreated中向主线程传递消息时报错
public void surfaceCreated(SurfaceHolder holder) {
Message msg = mh.obtainMessage();
msg.sendToTarget();
}
错误提示为: Can't create handler inside thread that has not called Looper.prepare()
问题发生在构造子类时就出错了,位置:
主类:
mPreview = new SurfaceView(MainActivity.this, h);
子类:
public SurfaceView(Context context, Handler h) {mh = h}
请问是咋回事啊

1个回答

starbenx
starbenx   2016.02.29 15:44

找到问题了,好像是surfaceview不能在子线程中构造,我把surfaceview的构造移到UI线程的handler中,然后在主类中用sendmessage触发就OK了

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!