定時器Timer 這個非常好用、在c語言中 用到的比較多,今天我就舉一個我在工作中用到的例子吧,先說一下我的需求。
我的需求是,我的用戶端給伺服器端發送資料,點擊一次發送以後,會先發送一條資料,伺服器接收到資料以後返回我一個標誌位代表接收完成,然後我在發另一條資料,伺服器再返回,這樣一直發送(自訂發送幾次)如果伺服器沒有返回那麼我就不發送,提示發送資訊失敗。
面對這樣的需求我遇到了幾個問題,①如何做到發送以後要等伺服器返回我才能發送第二條,②如果伺服器沒有返回我如何設定逾時
我也是一個新手,查了好長時間的資料總是處理不好這些問題,最後還是用到了定時器很好的解決了我的問題,不說了直接上代碼
我做的事android 程式,首先開進入主介面我會執行time()這個方法
private void time() {
Timer time = new Timer();
time.scheduleAtFixedRate(task, 100, 100);// 延時100毫秒、100毫秒執行一次,不斷執行
g_iWebRecTimeOutCnt = 0;
}
調用這個方法,會在進入主介面就開啟定時器,當滿足定時器的條件就會進入task,在這個time中我給他了一個全域的int 變數g_iWebRecTimeOutCnt 給他賦值為0,
然後建立了TimerTask 這個任務
private TimerTask task = new TimerTask() {// 由 Timer 安排為一次執行或重複執行的任務。
@Override
public void run() {
if (g_iWebRecTimeOutCnt > 0) {
g_iWebRecTimeOutCnt -= 1;
}
}
};
在這個任務中設定了 當變數g_iWebRecTimeOutCnt >0的時候會讓他0.1秒-1一次直到歸0;
現在定時器設定好了,下面開始用到定時器
builder.setPositiveButton("上傳", new DialogInterface.OnClickListener() {
@SuppressLint("ParserError")
public void onClick(DialogInterface dialog, int whichButton) {
showDialogSend();
userName = etUserName.getText().toString();
taskNo = etTaskNo.getText().toString();
deleteIDArray = new int[list.size()];
new Thread(sendNable).start();
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
builder.create().show();
呵呵這個我的一個上傳按鈕,點擊上傳顯示一個dialog“正在上傳” 開啟一個線程去做上傳的操作
Runnable sendNable = new Runnable() {
public void run() {//上傳的線程
count = xxx;//count是一個int的id
try {
if (WebSendSingleMemberData(count)) {//這個是我封裝的上傳一個構件的方法
// 發送成功,開始判斷是否有現場資訊
g_bSendError = false;//這是一個布爾的變數true表示 上傳失敗 false 表示上傳成功
if (WebSendSingleSiteData(pictureID)) {
// 如果現場資訊發送成功,開始判斷是夠有圖片資訊
g_bSendError = false;
picList = db
.selectAllPictureInfo1(pictureID);
if (picList.size() > 0) {
pictureID = "";
for (int i = 0; i < picList.size(); i++) {
if (webSendSinglePicData(i)) {
// 代表該圖片發送成功
g_bSendError = false;
} else {
// 代表strGoujian下的第i張圖片發送失敗
g_bSendError = true;
}
}
}
} else {
// 發送不成功,發送失敗strGoujian下的現場資訊發送失敗
g_bSendError = true;
}
}
} else {
// 發送不成功,提示構件資訊發送失敗count
g_bSendError = true;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (!g_bSendError) {//如果是false 表示成功
Message msgSuc = new Message();
msgSuc.what = 6;
mHandler.sendMessage(msgSuc);
} else {否則 表示失敗
Message msgerror = new Message();
msgerror.what = 7;
mHandler.sendMessage(msgerror);
}
}
};
上面主要是我的一個邏輯,只有一個發送成功才發送另一個,下面開始用到定時器
// 發送一個構件資訊的方法
private boolean WebSendSingleMemberData(int iDataBaseIndex)
throws UnsupportedEncodingException {
MemberInfo mem = db.selectMemberInfo(iDataBaseIndex);
byte buffer[];
String cont = mem.getMemberCnt();
strGoujian = mem.getMemberName();
pictureID = mem.getPictureID();
sitStatus = mem.getSiteInfoStatus();
length = getWordCount(cont) + 1;
buffer = initProtocal(1, "", "", length, strGoujian, userName, taskNo);//初始化協議頭,大家用不到
try {
bWebRecValid = sendMsg(buffer, cont);//這個方法是發送的,發送文本資訊都用這個方法
} catch (InterruptedException e) {
e.printStackTrace();
}
return bWebRecValid;
}
//發送文本資訊的封裝的方法
// 發送資料的方法
private boolean sendMsg(byte[] msg, String cont)
throws InterruptedException {
try {
out = socket.getOutputStream();
osw = new OutputStreamWriter(socket.getOutputStream(), "GBK");
in = socket.getInputStream();
writer = new BufferedWriter(osw);
out.write(msg);//這個是發送協議頭
char[] bCont = cont.toCharArray();
writer.write(bCont);//這個是發送資料
writer.flush();
int iAllRecBytes;
int iRecByte;
byte AllRecBuff[] = new byte[1024];
byte RecBuff[] = new byte[1024];
iAllRecBytes = 0;
g_iWebRecTimeOutCnt = 50; // 0.1秒 定時器 !!!! 在這裡給定時器設定成50, 50>0 就會進入定時器0.1秒去-1,知道歸0,只要是在這5秒鐘內伺服器有資料返回下面都可以接受
while (g_iWebRecTimeOutCnt > 0) { // 等待 5秒逾時
RecBuff = new byte[in.available()];
iRecByte = in.read(RecBuff);
if (iRecByte > 0) {//
for (int i = 0; i < iRecByte; i++) {
AllRecBuff[i + iAllRecBytes] = RecBuff[i];
}
iAllRecBytes += iRecByte;
if (iAllRecBytes == 732) {
byte[] ret = new byte[4];
ret[0] = RecBuff[224];
ret[1] = RecBuff[225];
ret[2] = RecBuff[226];
ret[3] = RecBuff[227];
n = toInt(ret);
if ((n >= 1) && (n <= 3)) {
// g_iWebRecTimeOutCnt = 0;
bWebRecValid = true;
break;
}
}
if (iAllRecBytes > 732) {
bWebRecValid = false;
break;
}
}
}
if (g_iWebRecTimeOutCnt == 0) {
// 5秒接收逾時, 提示逾時對話方塊,並退出!!!!! 如果5秒鐘已過,那麼定時器就歸0了, 就不能在進入上面的接收了 會在這裡設定bWebRecValid =false 表示發送失敗
bWebRecValid = false;
}
return bWebRecValid;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bWebRecValid;
}
好吧這就是我程式中的定時器的用法,本來打算分離出來的,不過分離出來 簡單的一個定時器 比較抽象,所以還是把自己項目中用法貼出來了,好好讀,你會有所收穫的!