从套接字连接更新View

时间:2011-04-19 00:27:43

标签: android sockets user-interface

我正在编写一个需要每隔10秒左右从套接字接收数据的应用程序,然后在屏幕上绘制一个视图来绘制该数据。不幸的是,我对Android很陌生,并且在理解如何使其工作方面遇到了一些麻烦。我一直在阅读处理程序,但我不太清楚如何使用它们。你可以在扩展View的类中使用它们,还是根本不需要使用它们?

1 个答案:

答案 0 :(得分:0)

使用Handler似乎是正确的方法,因为你是从非UI线程更新你的UI(至少你应该!)...你可以像这样使用Handler,或者从你的数据处理活动并从您的Activity中的Handler调用CustomView.draw()。

public class CustomView extends View {

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public CustomView(Context context) {
        super(context);
        ...
        startThread();
        ...
    }

    @Override
    public void onDraw(Canvas canvas) {
        ...
        //Do drawing...canvas.drawBitmap(bitmap) or w/e
        ...
    }

    private void startThread() {
        Thread thread = new Thread() {
            public void run() {
                try {
                    doSocketRequest();
                } catch (SocketException e) { // Or w/e exceptions are applicable
                    e.printStackTrace();
                } finally {
                    Message msg = new Message();
                    //msg.obj = ObjectContainingInformationTheHandlerMightNeed
                    mHandler.sendMessage(msg);//replace 0 w/ a message if need be

                }
            }
        };
    }

    private void doSocketRequest() {
        ...
        //Do your socket stuff here
        ...
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ...
            //Do graph processing stuff
            ...
            invalidate(); //forces onDraw
        }
    };

}