如何在handleMessage中使用类本地非静态变量时使android处理静态

时间:2015-11-09 05:40:15

标签: java android handler

此代码片段位于CircleView类视图

private Handler handler = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    {

        super.handleMessage(msg);
        if (curAng > 0 && curTime > 0) // this is non static varriable in class
        {
            curAng = curAng - (2 * Math.PI)/360;
        }
        else
        {
            curAng = 0; // this is non static variable in class
            task.cancel(); // this is non static variable in class
        }
        invalidate();
    }
};

我从stackoverflow尝试了几个解决方案,但对我来说没有任何作用。以下示例

static class MyInnerHandler extends Handler{
        WeakReference<CircleView> mFrag;

        MyInnerHandler(CircleView aview) {
            mFrag = new WeakReference<CircleView>(aview);
        }

        @Override
        public void handleMessage(Message msg)
        {

            super.handleMessage(msg);
            if (curAng > 0 && curTime > 0) // this is non static variable in class
            {
                curAng = curAng - (2 * Math.PI)/360;
            }
            else
            {
                curAng = 0; // this is non static variable in class
                task.cancel(); // this is non static variable in class
            }
            invalidate();
        }
    }
    MyInnerHandler myHandler = new MyInnerHandler(this);

问题是,如果我按照上面的代码我得到错误非静态字段不能从静态上下文引用。我不想将私有变量更改为静态。请帮忙谢谢。 (注意: - 我也在我的代码中的某处使用handler.obtainMessage().sendToTarget();)。

最后,我找到了解决方案,了解如何在不使其变为静态的情况下访问类变量。

这里是答案: -

 static class MyInnerHandler extends Handler{
    WeakReference<CircleView> mFrag;

    MyInnerHandler(CircleView aview) {
        mFrag = new WeakReference<CircleView>(aview);
    }

    @Override
    public void handleMessage(Message msg)
    {
        CircleView aview = mFrag.get(); // Here is solution. with aview. can access all method and variables.  
        super.handleMessage(msg);
        if (aview.curAng > 0 && aview.curTime > 0) // this is non static varriable in class
        {
            aview.curAng = curAng - (2 * Math.PI)/360;
        }
        else
        {
            aview.curAng = 0; // this is non static variable in class
            aview.task.cancel(); // this is non static variable in class
        }
        aview.invalidate();
    }
}
MyInnerHandler myHandler = new MyInnerHandler(this);

1 个答案:

答案 0 :(得分:0)

我认为除了你做的那样,你最好在继续之前检查aview是否为null。因为当一条消息发布到处理程序时,原始视图可能已经消失并且有机会被垃圾收集。

@Override
 public void handleMessage(Message msg)
 {

    super.handleMessage(msg);

    CircleView aview = mFrag.get(); // Here is solution. 
                    //with aview. can access all method and variables.  


    if (aview==null) return;

     ... ...
}