public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(LOG_TAG, "receive message " + msg.what);
MainActivity activity = weakReference.get();
if (activity==null){
//Activity已经回收,无需再处理UI了
return ;
}
//检查消息队列并移除未发送的消息,这主要是避免在复杂环境下消息出现重复等问题。
if (activity.handler.hasMessages(MSG_UPDATE_IMAGE)){
activity.handler.removeMessages(MSG_UPDATE_IMAGE);
}
switch (msg.what) {
case MSG_UPDATE_IMAGE:
currentItem++;
activity.viewPager.setCurrentItem(currentItem);
//准备下次播放
activity.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
break;
case MSG_KEEP_SILENT:
//只要不发送消息就暂停了
break;
case MSG_BREAK_SILENT:
activity.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
break;
case MSG_PAGE_CHANGED:
//记录当前的页号,避免播放的时候页面显示不正确。
currentItem = msg.arg1;
break;
default:
break;
}
}
}
集成代码:MainActivity
下面是MainActivity的代码,主要是加载View和对ViewPager进行初始化设置:
public class MainActivity extends Activity {
private static final String LOG_TAG = “MainActivity”;
private ImageHandler handler = new ImageHandler(new WeakReference(this));
private ViewPager viewPager;
@Override
protected void onCreate(Bu