Handler弱引用(倒计时)解决"Activity使用Handler时出现警告信息"的问题

倒计时

leftoverTime=600;10分钟倒计时
Message pushmessage = mHandler.obtainMessage(1);     // Message
mHandler.sendMessageDelayed(pushmessage, 1000);
private android.os.Handler mHandler = new CustomerHandler(MainActivity.this);
class CustomerHandler extends android.os.Handler{
//弱引用(引用外部类)
WeakReference mCls;
CustomerHandler(MainActivity cls) {
//构造弱引用
mCls = new WeakReference(cls);
}
@Override
public void handleMessage(Message msg) {
//通过弱引用获取外部类.
MainActivity cls = mCls.get();
//进行非空再操作
if (cls != null) {
switch (msg.what) {
case 1:
leftoverTime--;
if (leftoverTime <= 59) {
binding.tvTime.setText(String.format("00:%02d", leftoverTime));
} else {
binding.tvTime.setText(String.format("%02d:%02d", leftoverTime / 60, leftoverTime % 60));
}
Log.d("Mainhandler", "handleMessage: " + leftoverTime);
if (leftoverTime > 0) {
Message message = mHandler.obtainMessage(1);
mHandler.sendMessageDelayed(message, 1000); // send message
} else {
binding.lyPush.setVisibility(View.GONE);
mHandler.removeMessages(1);
}
break;
}
}
super.handleMessage(msg);
}
}

你可能感兴趣的:(Handler弱引用(倒计时)解决"Activity使用Handler时出现警告信息"的问题)