我想只在特定片段对用户可见时才运行处理程序,当该片段不可见时,我希望处理程序停止。我的问题是当我在顶部有另一个片段时处理程序正在运行。我的代码是(片段中的代码):
@Override
public void onResume() {
super.onResume();
updatedNotification();
}
private void updatedNotification() {
String alertInterval= TextUtils.isEmpty(prefManager.getKeyAlertTimeInterval())?"15":prefManager.getKeyAlertTimeInterval();
long timeInMillis = Long.parseLong(alertInterval)*1000;
runnable = new Runnable() {
@Override
public void run() {
updatedNotification();
}
};
handler= new Handler();
handler.postDelayed(runnable,timeInMillis);
}
@Override
public void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
答案 0 :(得分:1)
您可以尝试覆盖setUserVisibleHint
或setMenuVisibility
并在其中添加处理程序代码:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
updatedNotification();
} else {
handler.removeCallbacks(runnable);
}
}
或者
@Override
public void setMenuVisibility(final boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
updatedNotification();
} else {
handler.removeCallbacks(runnable);
}
}