将上下文传递给计时器......这是安全的

时间:2010-07-17 10:23:08

标签: android android-context

我正在使用需要上下文的计时器。 现在我有以下代码:

   mContext=context;
    mEventID=eventID;
    CountDownTimer cdTimer = new CountDownTimer(20000, 1000) {
        public void onTick(long millisUntilFinished) {
            // Do nothing onTick... Sorry
        }
        public void onFinish() {
            int deletedRows = mContext.getContentResolver().delete()
            // ..rest of code
        }
    };
    cdTimer.start();

这样使用是否安全,或者我可能会泄露上下文? 顺便说一句。这是broadcastreceiver

1 个答案:

答案 0 :(得分:2)

您不应该将Context传递给线程,而是通过它的父名称来引用它。

类似这样的事情

class MyClass {
...
CountDownTimer cdTimer = new CountDownTimer(20000, 1000) {
        public void onTick(long millisUntilFinished) {
            // Do nothing onTick... Sorry
        }
        public void onFinish() {
            int deletedRows = myClass.this.context.getContentResolver().delete()
            // ..rest of code
        }
    };

...

}

所以你可能需要通过广播接收者的名字来调用上下文,例如:MyReceiver.this.context假设context是该类的成员。