android-discuss icon indicating copy to clipboard operation
android-discuss copied to clipboard

关于 handler 的 post 方法

Open xisailuo opened this issue 11 years ago • 2 comments

既然 handler 的 post 方法相当于直接调用了 run 方法,为什么不直接调? 读SlidingMenuDemo的SlidingActivityHelper类想到的 new Handler().post(new Runnable() { public void run() { if (open) { if (secondary) { mSlidingMenu.showSecondaryMenu(false); } else { mSlidingMenu.showMenu(false); } } else { mSlidingMenu.showContent(false);
} } });

xisailuo avatar Nov 23 '15 14:11 xisailuo

  1. android的UI操作是单线程模型
  2. handler的post的方法实际上是调用sendMessageDelayed方法,即使是在子线程中调用post方法,最后还是在主线程中执行方法并能操作UI

qwe3243002 avatar Nov 24 '15 02:11 qwe3243002

谢谢回复,我原本纳闷本来方法就运行在主线程上,为啥还要new Handler().post(),现在想想主要为了程序健壮性的考虑,毕竟SlidingActivityHelper类是个自定义的类

xisailuo avatar Nov 25 '15 01:11 xisailuo