从套接字连接更新视图

| 我正在编写一个需要每10秒钟左右从套接字接收一次数据的应用程序,然后在屏幕上绘制一个视图以绘制该数据的图形。不幸的是,我是Android的新手,在理解如何实现此功能方面遇到了一些麻烦。我一直在阅读处理程序,但是我不太确定如何使用它们。您可以将它们与扩展View的类一起使用,还是根本不需要使用它们?
已邀请:
使用处理程序似乎是正确的方法,因为您是从非UI线程更新UI(至少应该如此!)...您可以像这样使用Handler,也可以从Activity中进行数据处理并调用您的Activity中的处理程序中的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
        }
    };

}

要回复问题请先登录注册