通过 android studio 运行代码检查后,它突出显示 MainHandler 应该是静态的。我将类(class)移至静态但现在它提示说 “无法从静态上下文中引用非静态方法 remainingSecondsChanged(int)”
public class CountDownView extends FrameLayout {
private static void remainingSecondsChanged(int newVal) {
mRemainingSecs = newVal;
if (mListener != null) {
mListener.onRemainingSecondsChanged(mRemainingSecs);
}
if (newVal == 0) {
// Countdown has finished.
setVisibility(View.INVISIBLE);
if (mListener != null) {
mRemainingSecondsView.setText(null);
mRemainingSecondsView.setBackgroundResource(R.drawable.bracket_view_finder);
mListener.onCountDownFinished();
}
} else {
Locale locale = getResources().getConfiguration().locale;
String localizedValue = String.format(locale, "%d", newVal);
mRemainingSecondsView.setText(localizedValue);
// Schedule the next remainingSecondsChanged() call in 1 second
mHandler.sendEmptyMessageDelayed(SET_TIMER_TEXT, 1000);
}
}
public void startCountDown(int sec) {
if (sec < 0) {
return;
}
if (sec == 0) {
cancelCountDown();
}
mRemainingSecondsView.setBackgroundResource(R.drawable.bracket_count_down);
setVisibility(View.VISIBLE);
remainingSecondsChanged(sec);
}
private static class MainHandler extends Handler {
@Override
public void handleMessage(Message message) {
if (message.what == SET_TIMER_TEXT) {
remainingSecondsChanged(mRemainingSecs - 1);
}
}
}
private static final MainHandler mHandler = new MainHandler();
}
知道如何解决吗?
最佳答案
首先...为什么 Studio 会显示该消息?
背景
每个 Handler
都与一个 Thread
相关联,并且同一 Thread
上的所有 Handler
对象共享一个公共(public)的Looper
对象,他们在其中发布和阅读消息。事情是......当这些对象是非静态的......非静态内部类持有对其外部类的隐式引用。所以 Handler
将保存对您的 Activity
的引用,如果此 Handler
有延迟消息,您的 Activity
在处理此消息之前,将无法进行垃圾回收。
您可以阅读更多相关信息 here .
解决方案
至于你的问题。您已经做的第一件事是使您的 Handler
成为 static
内部类。现在,为您的外部类创建一个 WeakReference
(可以是一个 Activity
,或者我相信在这种情况下,您的 CountDownView
)。
现在尝试将您的 Handler
更改为类似这样的内容(而不是 Activity
,您可以引用您的 CountDownView
):
private static class MainHandler extends Handler {
private final WeakReference<YourActivity> mActivity;
public MainHandler(YourActivity activity) {
mActivity = new WeakReference<YourActivity>(activity);
}
@Override
public void handleMessage(Message message) {
YourActivity activity = mActivity.get();
if (activity != null) {
if (message.what == SET_TIMER_TEXT) {
activity.remainingSecondsChanged(mRemainingSecs - 1);
}
}
}
}
然后像这样实例化它:
// this is a reference to your Activity, or your CountDownView, wherever your method is.
private final MainHandler mHandler = new MainHandler(this);
关于android - 非静态方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31850239/