我在编写java程序的时候经常要注册监听器,相应事件发生,现在我们自己来编写个listener,自己实现并回调它。
在业务逻辑中有时候在存储数据,有网络超时等现象,现在就编写一个超时listener。重写android中的progressdialog,在其中添加超时监听器。
自己的业务逻辑中实现回调接口,超时并回调自己实现的函数。
代码:
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
public class ProgressDialog extends android.app.ProgressDialog {
public static final String TAG = "ProgressDialog";
private long mTimeOut = 0;// 默认timeOut为0即无限大
private OnTimeOutListener mTimeOutListener = null;// timeOut后的处理器
private Timer mTimer = null;// 定时器
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(mTimeOutListener != null){
mTimeOutListener.onTimeOut(ProgressDialog.this);
dismiss();
}
}
};
public ProgressDialog(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
/**
* 设置timeOut长度,和处理器
*
* @param t
* timeout时间长度
* @param timeOutListener
* 超时后的处理器
*/
public void setTimeOut(long t, OnTimeOutListener timeOutListener) {
mTimeOut = t;
if (timeOutListener != null) {
this.mTimeOutListener = timeOutListener;
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
if (mTimeOut != 0) {
mTimer = new Timer();
TimerTask timerTast = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
// dismiss();
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
};
mTimer.schedule(timerTast, mTimeOut);
}
}
/**
* 通过静态Create的方式创建一个实例对象
*
* @param context
* @param time
* timeout时间长度
* @param listener
* timeOutListener 超时后的处理器
* @return MyProgressDialog 对象
*/
public static ProgressDialog createProgressDialog(Context context,
long time, OnTimeOutListener listener) {
ProgressDialog progressDialog = new ProgressDialog(context);
if (time != 0) {
progressDialog.setTimeOut(time, listener);
}
return progressDialog;
}
/**
*
* 处理超时的的接口
*
*/
public interface OnTimeOutListener {
/**
* 当progressDialog超时时调用此方法
*/
abstract public void onTimeOut(ProgressDialog dialog);
}
}
重写好了,在业务逻辑使用到它:
先导入该类和该类的接口:
import cn.edu.wtu.dialoglistener.ProgressDialog;
import cn.edu.wtu.dialoglistener.ProgressDialog.OnTimeOutListener;
ProgressDialog mProgressDialog = ProgressDialog.createProgressDialog(this, Globals.TIMEOUT_CONNECT_WAITING, new OnTimeOutListener(){
@Override
public void onTimeOut(ProgressDialog dialog) {
// TODO Auto-generated method stub
Toast.makeText(PersonalProfileActivity.this, R.string.message_prompt_connecting_timeout, Toast.LENGTH_SHORT).show();
}
});
ok,只要到时候使用show函数,就可以显示了,超过时间就会有toast弹出,也可以由其他业务处理。