轮询超时/执行 案例

说明:这是在项目中用到的  实际操作请截取部分有关的片段【标记】

方便自己也方便大家


以后实现这个类中的接口即可

package org.bojoy.core.utils;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;

/**
 * 
 * @author luzhenyu
 * PollingTimeOutTask 轮询超时任务
 * 
 */
public class PollingTimeoutTask {

	@SuppressWarnings("unused")
	private final String TAG = PollingTimeoutTask.class.getSimpleName();
	
	private boolean start;
	private int timeCounter;
	private int period;
	private int maxTime;
	private int delay;
	private Handler handler = new Handler();
	private PollingListener listener;
	private Timer timer;
	private TimerTask task = new TimerTask() {
		
		@Override
		public void run() {
//			LogProxy.i(TAG, "task run");
			handler.post(new Runnable() {
				
				@Override
				public void run() {
					/** 不超时处理 */
					if (maxTime == 0) {
						listener.onExecute();
					} else {
						if (timeCounter < maxTime) {
							listener.onExecute();
							timeCounter += period;
						} else {
							listener.onTimeout();
							suspendPolling();
						}
					}
				}
			});
		}
	};
	
	/**
	 * 
	 * @param period —— 间隔时间(单位:毫秒)
	 * @param delay —— 延迟时间(单位:毫秒)
	 * @param maxTime —— 超时时间(单位:毫秒) 0-表示不超时处理
	 * @param listener —— 轮询监听接口
	 */
	public PollingTimeoutTask(int period, int delay, int maxTime, PollingListener listener) {
		this(period, delay, maxTime, listener, null);
	}
	
	/**
	 * 
	 * @param period —— 间隔时间(单位:毫秒)
	 * @param delay —— 延迟时间(单位:毫秒)
	 * @param maxTime —— 超时时间(单位:毫秒) 0-表示不超时处理
	 * @param listener —— 轮询监听接口
	 * @param handler
	 */
	public PollingTimeoutTask(int period, int delay, int maxTime, PollingListener listener, Handler handler) {
		this.period = period;
		this.maxTime = maxTime;
		this.delay = delay;
		if (handler != null) {
			this.handler = handler;
		}
		if (listener == null) {
			throw new IllegalArgumentException("PollingListener can not null");
		}
		this.listener = listener;
		timer = new Timer();
	}
	
	public void startPolling() {
		start = true;
		timeCounter = 0;
		timer.schedule(task, delay, period);
	}
	
	public void suspendPolling() {
		if (start) {
			task.cancel();
			timer.cancel();
			task = null;
			timer = null;
			start = false;
		}
	}

	public boolean isStart() {
		return start;
	}

	public interface PollingListener {
		
		public void onExecute();
		public void onTimeout();
		
	}
}
实现的例子

package org.bojoy.gamefriendsdk.app.utils;

import org.bojoy.core.utils.PollingTimeoutTask;
import org.bojoy.core.utils.PollingTimeoutTask.PollingListener;

import de.greenrobot.event.EventBus;

/**
 * 
 * @author luzhenyu
 * GlobalPollingTimeoutTool 全局的轮询超时工具类
 * 
 */
public class GlobalPollingTimeoutTool implements PollingListener {
	
	private final String TAG = GlobalPollingTimeoutTool.class.getSimpleName();
	
	private static GlobalPollingTimeoutTool instance;
	private final static Object block = new Object();
	private PollingTimeoutTask pollingTask;
	private EventBus eventBus = EventBus.getDefault();
	private String taskTag;

	private GlobalPollingTimeoutTool() {
		
	}
	
	public static GlobalPollingTimeoutTool getDefault() {
		if (instance == null) {
			synchronized (block) {
				if (instance == null) {
					instance = new GlobalPollingTimeoutTool();
				}
			}
		}
		return instance;
	}
	
	/**
	 * 启动全局的轮询事件
	 * @param period
	 * @param delay
	 * @param maxTime
	 * @param tag
	 * @return 返回是否启动成功,如果不成功,说明有轮询超时再用,要合理判断后先中断,后启动
	 */
	public boolean startPollingTask(int period, int delay, int maxTime, String tag) {
		if (pollingTask != null && pollingTask.isStart()) {
			return false;
		}
		taskTag = tag;
		pollingTask = null;
		pollingTask = new PollingTimeoutTask(period, delay, maxTime, this);
		pollingTask.startPolling();
		return true;
	}
	
	/**
	 * 中断轮询事件
	 */
	public void suspendGlobalPolling() {
		if (pollingTask != null && pollingTask.isStart()) {
			pollingTask.suspendPolling();
		}
		pollingTask = null;
	}

	public String getTaskTag() {
		return taskTag;
	}
	
	public boolean isStart(String tag) {
		if (tag == null) {
			throw new IllegalArgumentException("Tag not null");
		}
		if (pollingTask == null) {
			return false;
		}
		if (tag.equals(taskTag)) {
			return pollingTask.isStart();
		}
		return false;
	}

	@Override
	public void onExecute() {
		eventBus.post(new PollingExecuteEvent(taskTag));
	}

	@Override
	public void onTimeout() {
		eventBus.post(new PollingTimeoutEvent(taskTag));
	}

	public class PollingExecuteEvent {
		
		private String taskTag;
		
		public PollingExecuteEvent(String tag) {
			taskTag = tag;
		}

		public String getTaskTag() {
			return taskTag;
		}

	}
	
	public class PollingTimeoutEvent {
		
		private String taskTag;
		
		public PollingTimeoutEvent(String tag) {
			taskTag = tag;
		}

		public String getTaskTag() {
			return taskTag;
		}

	}
}

在activity.java 中这样使用

package org.bojoy.gamefriendsdk.app.dock.page.impl;

import org.bojoy.BJMGFCommon;
import org.bojoy.core.utils.ReflectResourceId;
import org.bojoy.gamefriendsdk.Resource;
import org.bojoy.gamefriendsdk.app.communication.request.BaseRequestSession;
import org.bojoy.gamefriendsdk.app.dock.activity.BJMGFActivity;
import org.bojoy.gamefriendsdk.app.dock.page.BaseActivityPage;
import org.bojoy.gamefriendsdk.app.eventhandler.event.BaseReceiveEvent;
import org.bojoy.gamefriendsdk.app.screen.page.PageManager;
import org.bojoy.gamefriendsdk.app.screen.widget.ClearEditText;
import org.bojoy.gamefriendsdk.app.utils.GlobalPollingTimeoutTool;
import org.bojoy.gamefriendsdk.app.utils.GlobalPollingTimeoutTool.PollingExecuteEvent;
import org.bojoy.gamefriendsdk.app.utils.GlobalPollingTimeoutTool.PollingTimeoutEvent;

import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 
 * @author luzhenyu
 * DockCheckPhonePage 检验手机号页面
 *
 */
public class DockCheckPhonePage extends BaseActivityPage {
	
	private final String TAG = DockModifyPhonePage.class.getSimpleName();
	
	private final int Timeout_Max = 60 * 2;
	private int period = 1000,delay = 0, maxTime = 1000 * 60 * 2, resendTime = Timeout_Max;
	private LinearLayout mBackLayout = null;
	private TextView mToastTextView = null;
	private ClearEditText mCodeEditText = null;
	private TextView mReSendTextView,mTimeTextView;
	private Button mSureButton = null;
	/** bug 修复2 */
	/** 新增随软键盘状态变化的控件 */
	private View keyboardView;
	
	private GlobalPollingTimeoutTool globalPolling = GlobalPollingTimeoutTool.getDefault();//【标记】
	
	public DockCheckPhonePage(Context context,
			PageManager manager, BJMGFActivity activity) {
		super(ReflectResourceId.getLayoutId(context, 
				Resource.layout.bjmgf_sdk_dock_account_checkphone), context, manager, activity);
	}

	public void onCreateView(View view) {
		mBackLayout = (LinearLayout)view.findViewById(ReflectResourceId.getViewId(context, 
				Resource.id.bjmgf_sdk_float_account_manager_checkphone_backLlId));
		mToastTextView = (TextView)view.findViewById(ReflectResourceId.getViewId(context, 
				Resource.id.bjmgf_sdk_float_account_manager_checkphone_messageToastTextViewId));
		mReSendTextView = (TextView)view.findViewById(ReflectResourceId.getViewId(context, 
				Resource.id.bjmgf_sdk_float_account_manager_checkphone_resendTextViewId));
		mSureButton = (Button)view.findViewById(ReflectResourceId.getViewId(context, 
				Resource.id.bjmgf_sdk_float_account_manager_checkphone_buttonId));
		mCodeEditText = (ClearEditText)view.findViewById(ReflectResourceId.getViewId(context,
				Resource.id.bjmgf_sdk_float_account_manager_checkphone_editTextId));
		mTimeTextView = (TextView)view.findViewById(ReflectResourceId.getViewId(context,
				Resource.id.bjmgf_sdk_checkPhoneTimeTvId));
		keyboardView = (View)view.findViewById(ReflectResourceId.getViewId(context, 
				Resource.id.bjmgf_sdk_float_account_manager_checkphone_keyboard));
		
		mBackLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				manager.previousPage();
			}
		});
		
		mReSendTextView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				/** bug 修复1 */
				/** 增加全局轮询解决 短信发送太快 TimeTask的异常崩溃 */
				// 重发
				resendTime = Timeout_Max;
				globalPolling.startPollingTask(period, delay, maxTime, TAG);//【标记】
				showProgressDialog();
				communicator.sendRequest(BaseRequestSession.Request_BindPhone,BJMGFCommon.getMobile());//绑定重发
			}
		});
		
		mSureButton.setOnClickListener(new View.OnClickListener() {
			// 验证码验证
			@Override
			public void onClick(View arg0) {
				if (checkVerifyCodeLength(mCodeEditText.getEditText())) {
					showProgressDialog();
					communicator.sendRequest(BaseRequestSession.Request_BindPhone_Check_Code, mCodeEditText.getEditText());//手机绑定验证码验证
				}else {
					showToast(getString(Resource.string.bjmgf_sdk_register_dialog_checkVerifyCodeErrorStr));
				}
				
			}
		});
		/** bug 修复1 */
		/** 增加全局轮询解决 短信发送太快 TimeTask的异常崩溃 */
		globalPolling.startPollingTask(period, delay, maxTime, TAG);
		super.onCreateView(view);
	}
	
	@Override
	public void createdSendHttp() {
		
	}

	@Override
	public void setView() {
		String str = mToastTextView.getText().toString();
		/**
		 * 按照格式输出"xxxxxx158****5454xxxxxx"
		 * */
		mToastTextView.setText(String.format(str, transformPhoneNumberType(BJMGFCommon.getMobile())));
		resetTimeText();
	}

	/** bug 修复2 */
	/** 新增随软键盘状态变化的控件 */
	@Override
	public View getKeyboardView() {
		return keyboardView;
	}
	
	/**
	 * 修复bug 1
	 * 添加倒计时
	 * */
	private String resetTimeText() {
		return String.format(context.getResources().getString(ReflectResourceId.getStringId(context,
				Resource.string.bjmgf_sdk_floatWindow_accountManager_checkPhone_receiveCodeToastLeftStr)), 
				resendTime);
	}
	public void onEventMainThread(BaseReceiveEvent revEvent) {

		if (revEvent.getRequestType() == BaseRequestSession.Request_BindPhone_Check_Code) {
			dismissProgressDialog();
			if (revEvent.isSuccess()) {
				if (globalPolling != null) {
					globalPolling.suspendGlobalPolling();//【标记】
				}
				showToast(getString(Resource.string.bjmgf_sdk_BindPhoneSuccessedStr));
				DockAccountPage page = new DockAccountPage(context, manager, activity);
				manager.clearTopPage(page);
			}
		} else 
		if (revEvent.getRequestType() == BaseRequestSession.Request_BindPhone) {
			dismissProgressDialog();
			if (revEvent.isSuccess()) {
				showToast(getString(Resource.string.bjmgf_sdk_resendVerifyCodeStr));
			}
		}
	}
	
	public void onEventMainThread(PollingExecuteEvent executeEvent) {//【标记】
		if (executeEvent.getTaskTag().equals(TAG)) {
			resendTime--;
			mTimeTextView.setText(resetTimeText());	
		}
	}
	
	public void onEventMainThread(PollingTimeoutEvent timeoutEvent) {//【标记】
		if (timeoutEvent.getTaskTag().equals(TAG)) {
			initPollingRsendTv(true);
		}
	}
	
	private void initPollingRsendTv(boolean start) {
		mReSendTextView.setVisibility(start? View.VISIBLE : View.GONE);
	}
}

再比如  做一个一直轮询的任务  同样实现该接口  只是不做超时处理

package org.bojoy.gamefriendsdk.app.utils;

import org.bojoy.BJMGFCommon;
import org.bojoy.core.utils.LogProxy;
import org.bojoy.core.utils.PollingTimeoutTask;
import org.bojoy.core.utils.PollingTimeoutTask.PollingListener;
import org.bojoy.core.utils.Util;
import org.bojoy.gamefriendsdk.app.BJMGFSdk;
import org.bojoy.gamefriendsdk.app.communication.Communicator;
import org.bojoy.gamefriendsdk.app.communication.request.BaseRequestSession;
import org.bojoy.gamefriendsdk.app.eventhandler.event.BJMGFSdkEvent;
import org.bojoy.gamefriendsdk.app.eventhandler.event.BaseReceiveEvent;
import org.bojoy.gamefriendsdk.app.model.BJMGFGlobalData;
import org.bojoy.gamefriendsdk.app.widget.pulltorefresh.internal.Utils;

import de.greenrobot.event.EventBus;

/**
 * @author luzhenyu
 * MessagePollingTool  消息通知5分钟轮询查询新的离线消息
 * */
public class MessagePollingTool implements PollingListener {
	
	private PollingTimeoutTask task;
	private EventBus eventBus = EventBus.getDefault();
	private BJMGFGlobalData bjmgfData = BJMGFGlobalData.getDefault();
	public void start() {
		task = new PollingTimeoutTask(5 * 60 *1000, 1000, 0, this); 
		task.startPolling();
		eventBus.register(this);
	}
	
	public void stop() {//在必要时是要关闭的
		if (task == null || !task.isStart()) {
			return;
		}
		task.suspendPolling();
		task = null;
		eventBus.unregister(this);
	}
	
	@Override
	public void onExecute() {
		Communicator communicator = BJMGFSdk.getDefault().getCommunicator();
		if (Util.stringIsEmpty(BJMGFCommon.getOfflineTime())) {
			if (Util.stringIsEmpty(bjmgfData.get_OfflineTime())) {
				communicator.sendRequest(BaseRequestSession.Request_Message_Offline);
			}else {
				BJMGFCommon.setOfflineTime(bjmgfData.get_OfflineTime());
				communicator.sendRequest(BaseRequestSession.Request_Message_Offline);
			}
		} else {
			communicator.sendRequest(BaseRequestSession.Request_Message_Offline);
		}
	}

	@Override
	public void onTimeout() {
	<span style="white-space:pre">	</span>//不作处理
	}

	public void onEventMainThread(BaseReceiveEvent revEvent) {
		if (revEvent.getRequestType() == BaseRequestSession.Request_Message_Offline) {
			if (revEvent.isSuccess()) {
				if (Util.stringIsEmpty(BJMGFCommon.getOfflineTime())) {
					bjmgfData.saveOfflineTime("0");
				} else {
					bjmgfData.saveOfflineTime(BJMGFCommon.getOfflineTime());
				}
				eventBus.post(new BJMGFSdkEvent(BJMGFSdkEvent.Get_Offline_Message));
			}
		}
	}
	
}


关于里面用到的EventBus

传送门:

de.greenrobot.event.EventBus
https://github.com/greenrobot/EventBus

送上福利(好用的开源项目)

http://blog.csdn.net/qq530918474/article/details/38920265


【欢迎上码】

【微信公众号搜索 h2o2s2】


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值