2

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

   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.

4

1 回答 1

2

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

像这样的东西

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是该类的成员。

于 2010-07-19T10:42:25.993 回答