【Android面试】你造吗?invalidate和postinvalidate有这些区别

不知道小伙伴有没有这样的疑问:我们好像经常使用invalidate,但是对于postinvalidate好像也用到过,仔细回味,也说不清他们之间到底有什么区别。

一、区别与联系

1、postInvalidate() 方法在非 UI 线程中调用,通知 UI 线程重绘。

2、invalidate()方法在 UI 线程中调用,重绘当前 UI。Invalidate不能直接在线程中调用,因为他是违背了单线程模型:Android UI操作并不是线程安全的,并且这些操作必须在UI线程中调用。

二、使用情景

1.利用invalidate()刷新界面
实例化一个Handler对象,并重写handleMessage方法调用invalidate()实现界面刷新;而在线程中通过sendMessage发送界面更新消息。

// 在onCreate()中开启线程  
new  Thread( new  GameThread()).start();

// 实例化一个handler
Handler myHandler = new  Handler() {
    // 接收到消息后处理
    public   void  handleMessage(Message msg) {
        switch  (msg.what) {
        case  Activity01.REFRESH:
            mGameView.invalidate(); // 刷新界面
            break ;  
        }
        super .handleMessage(msg);
    }
};

class  GameThread  implements  Runnable {
    public   void  run() {
        while  (!Thread.currentThread().isInterrupted()) {
            Message message = new  Message();
            message.what = Activity01.REFRESH;
            // 发送消息
            Activity01.this .myHandler.sendMessage(message);
            try {
                Thread.sleep(100 );  
            } catch  (InterruptedException e) {  
                Thread.currentThread().interrupt();  
            }  
        }  
    }  
};

2.使用postInvalidate()刷新界面
使用postInvalidate则比较简单,不需要handler,直接在线程中调用postInvalidate即可。

class  GameThread  implements  Runnable {  
    public   void  run() {  
        while  (!Thread.currentThread().isInterrupted()) {  
            try  {  
                Thread.sleep(100 );  
            } catch  (InterruptedException e) {  
                Thread.currentThread().interrupt();  
            }  
            // 使用postInvalidate可以直接在线程中更新界面   
            mGameView.postInvalidate();  
        }  
    }  
}

三、源码解析

四、总结

可见postInvalidate底层是也是使用了Handler,这就是为什么能在子线程更新UI的原因。同时postInvalidate可以指定一个延迟时间。

微信扫一扫或者长按二维码关注我的微信公众号


【程序猿小白成长记】定期分享各类Java、Android等知识

你可能感兴趣的:(Android面试/基础)