Commit b88d7729 by patpat

替换为TimerHelper的timeout和loop

parent 6f114843
package com.bgycc.smartcanteen.action; package com.bgycc.smartcanteen.action;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public abstract class Action { public abstract class Action {
public enum State { public enum State {
...@@ -53,40 +49,6 @@ public abstract class Action { ...@@ -53,40 +49,6 @@ public abstract class Action {
return mAction.equals(action); return mAction.equals(action);
} }
protected void timeout(final Runnable runnable, long ms) {
Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
@Override
public void run() {
try {
if (runnable != null) runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, ms, TimeUnit.MILLISECONDS);
}
protected void loop(final Runnable runnable, final Runnable endRunnable, final int times, long period) {
final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
int count = 0;
@Override
public void run() {
try {
if (count >= times) {
if (endRunnable != null) endRunnable.run();
exec.shutdown();
return;
}
count++;
if (runnable != null) runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, period, TimeUnit.MILLISECONDS);
}
protected void success(String message) { protected void success(String message) {
if (mActionResult != null) mActionResult.onSuccess(message); if (mActionResult != null) mActionResult.onSuccess(message);
} }
......
...@@ -3,6 +3,7 @@ package com.bgycc.smartcanteen.action; ...@@ -3,6 +3,7 @@ package com.bgycc.smartcanteen.action;
import com.bgycc.smartcanteen.App; import com.bgycc.smartcanteen.App;
import com.bgycc.smartcanteen.Storage.PayStorage; import com.bgycc.smartcanteen.Storage.PayStorage;
import com.bgycc.smartcanteen.event.PayStateEvent; import com.bgycc.smartcanteen.event.PayStateEvent;
import com.bgycc.smartcanteen.helper.TimerHelper;
import com.bgycc.smartcanteen.server.websocket.MainWebSocket; import com.bgycc.smartcanteen.server.websocket.MainWebSocket;
import com.bgycc.smartcanteen.task.QRCodeTask; import com.bgycc.smartcanteen.task.QRCodeTask;
import com.bgycc.smartcanteen.util.DateUtil; import com.bgycc.smartcanteen.util.DateUtil;
...@@ -48,7 +49,7 @@ public class PayOfflineAction extends Action { ...@@ -48,7 +49,7 @@ public class PayOfflineAction extends Action {
break; break;
case FAIL: case FAIL:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.FAIL, message)); EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.FAIL, message));
timeout(new Runnable() { TimerHelper.INSTANCE.timeout(new Runnable() {
@Override @Override
public void run() { public void run() {
setState(State.INITED); setState(State.INITED);
...@@ -57,7 +58,7 @@ public class PayOfflineAction extends Action { ...@@ -57,7 +58,7 @@ public class PayOfflineAction extends Action {
break; break;
case RESQUEST_SUCCESS: case RESQUEST_SUCCESS:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.SUCCESS, message)); EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.SUCCESS, message));
timeout(new Runnable() { TimerHelper.INSTANCE.timeout(new Runnable() {
@Override @Override
public void run() { public void run() {
setState(State.INITED); setState(State.INITED);
......
...@@ -3,6 +3,7 @@ package com.bgycc.smartcanteen.action; ...@@ -3,6 +3,7 @@ package com.bgycc.smartcanteen.action;
import android.util.Log; import android.util.Log;
import com.bgycc.smartcanteen.App; import com.bgycc.smartcanteen.App;
import com.bgycc.smartcanteen.event.PayStateEvent; import com.bgycc.smartcanteen.event.PayStateEvent;
import com.bgycc.smartcanteen.helper.TimerHelper;
import com.bgycc.smartcanteen.server.websocket.MainWebSocket; import com.bgycc.smartcanteen.server.websocket.MainWebSocket;
import com.bgycc.smartcanteen.util.DateUtil; import com.bgycc.smartcanteen.util.DateUtil;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
...@@ -25,14 +26,19 @@ public class PayOnlineAction extends Action { ...@@ -25,14 +26,19 @@ public class PayOnlineAction extends Action {
} }
private String mPayCode; private String mPayCode;
private boolean mWaitResponse; private long mResponseTimeoutId = -1;
public PayOnlineAction() { public PayOnlineAction() {
super(ActionEnum.PAY_ONLINE.name()); super(ActionEnum.PAY_ONLINE.name());
MainWebSocket.subscribe(ActionEnum.PAY_RESULT.name(), mPayResultResponse); MainWebSocket.subscribe(ActionEnum.PAY_RESULT.name(), mPayResultResponse);
} }
protected void setState(State state, String message) { private void cancelResponseTimeout() {
TimerHelper.INSTANCE.cancel(mResponseTimeoutId);
mResponseTimeoutId = -1;
}
private void setState(State state, String message) {
if (state != getState()) { if (state != getState()) {
switch (state) { switch (state) {
case INITED: case INITED:
...@@ -40,25 +46,22 @@ public class PayOnlineAction extends Action { ...@@ -40,25 +46,22 @@ public class PayOnlineAction extends Action {
break; break;
case STARTED: case STARTED:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.WAIT, message)); EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.WAIT, message));
mWaitResponse = false; cancelResponseTimeout();
break; break;
case RESQUEST_SUCCESS: case RESQUEST_SUCCESS:
mWaitResponse = true; mResponseTimeoutId = TimerHelper.INSTANCE.timeout(new Runnable() {
timeout(new Runnable() {
@Override @Override
public void run() { public void run() {
if (!mWaitResponse) return;
setState(State.RESPONSE_TIMEOUT, "交易失败"); setState(State.RESPONSE_TIMEOUT, "交易失败");
} }
}, 10000); }, 10000);
break; break;
case RESPONSE_SUCCESS: case RESPONSE_SUCCESS:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.SUCCESS, message)); EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.SUCCESS, message));
mWaitResponse = false; cancelResponseTimeout();
mPayCode = ""; mPayCode = "";
success(message); success(message);
timeout(new Runnable() { TimerHelper.INSTANCE.timeout(new Runnable() {
@Override @Override
public void run() { public void run() {
setState(State.INITED, ""); setState(State.INITED, "");
...@@ -70,10 +73,10 @@ public class PayOnlineAction extends Action { ...@@ -70,10 +73,10 @@ public class PayOnlineAction extends Action {
case RESPONSE_FAIL: case RESPONSE_FAIL:
case RESPONSE_TIMEOUT: case RESPONSE_TIMEOUT:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.FAIL, message)); EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.FAIL, message));
mWaitResponse = false; cancelResponseTimeout();
mPayCode = ""; mPayCode = "";
fail(message); fail(message);
timeout(new Runnable() { TimerHelper.INSTANCE.timeout(new Runnable() {
@Override @Override
public void run() { public void run() {
setState(State.INITED, ""); setState(State.INITED, "");
...@@ -97,27 +100,25 @@ public class PayOnlineAction extends Action { ...@@ -97,27 +100,25 @@ public class PayOnlineAction extends Action {
setActionResult(result); setActionResult(result);
mPayCode = payCode; mPayCode = payCode;
final long timeoutId = TimerHelper.INSTANCE.timeout(new Runnable() {
@Override
public void run() {
setState(State.RESQUEST_TIMEOUT, "交易失败");
}
}, 10000);
final MainWebSocket.Response response = new MainWebSocket.Response() { final MainWebSocket.Response response = new MainWebSocket.Response() {
@Override @Override
protected void onSuccess(JSONObject data, String message) { protected void onSuccess(JSONObject data, String message) {
cancel(); TimerHelper.INSTANCE.cancel(timeoutId);
setState(State.RESQUEST_SUCCESS, message); setState(State.RESQUEST_SUCCESS, message);
} }
@Override @Override
protected void onFail(JSONObject data, String message, String code) { protected void onFail(JSONObject data, String message, String code) {
cancel(); TimerHelper.INSTANCE.cancel(timeoutId);
setState(State.RESQUEST_FAIL, message); setState(State.RESQUEST_FAIL, message);
} }
}; };
timeout(new Runnable() {
@Override
public void run() {
if (response.isCancelled()) return;
response.cancel();
setState(State.RESQUEST_TIMEOUT, "交易失败");
}
}, 10000);
try { try {
JSONObject params = new JSONObject(); JSONObject params = new JSONObject();
......
...@@ -44,7 +44,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) { ...@@ -44,7 +44,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
EventBus.getDefault().post(WifiStateEvent(1, "正在启动Wifi")) EventBus.getDefault().post(WifiStateEvent(1, "正在启动Wifi"))
if (!WifiHelpler.setEnable(true)) { if (!WifiHelpler.setEnable(true)) {
EventBus.getDefault().post(WifiStateEvent(1, "无法启动Wifi")) EventBus.getDefault().post(WifiStateEvent(1, "无法启动Wifi"))
timeout({ TimerHelper.timeout({
state = State.INITED state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1)) EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000) }, 3000)
...@@ -55,7 +55,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) { ...@@ -55,7 +55,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
val config = WifiHelpler.createWifiConfiguration(ssid, identity, pwd, type) val config = WifiHelpler.createWifiConfiguration(ssid, identity, pwd, type)
if (config == null) { if (config == null) {
EventBus.getDefault().post(WifiStateEvent(10, "Wifi参数有误")) EventBus.getDefault().post(WifiStateEvent(10, "Wifi参数有误"))
timeout({ TimerHelper.timeout({
state = State.INITED state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1)) EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000) }, 3000)
...@@ -68,7 +68,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) { ...@@ -68,7 +68,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
if (!WifiHelpler.enableNetwork(netId)) throw Exception("无法应用Wifi配置") if (!WifiHelpler.enableNetwork(netId)) throw Exception("无法应用Wifi配置")
} catch (e: Exception) { } catch (e: Exception) {
EventBus.getDefault().post(WifiStateEvent(20, e.message)) EventBus.getDefault().post(WifiStateEvent(20, e.message))
timeout({ TimerHelper.timeout({
state = State.INITED state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1)) EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000) }, 3000)
...@@ -81,7 +81,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) { ...@@ -81,7 +81,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
if (state == State.STARTED) { if (state == State.STARTED) {
state = State.FAIL state = State.FAIL
EventBus.getDefault().post(WifiStateEvent(30, "无法连接Wifi")) EventBus.getDefault().post(WifiStateEvent(30, "无法连接Wifi"))
timeout({ TimerHelper.timeout({
state = State.INITED state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1)) EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000) }, 3000)
...@@ -93,7 +93,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) { ...@@ -93,7 +93,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
if (info.ipAddress != 0) { if (info.ipAddress != 0) {
state = State.SUCCESS state = State.SUCCESS
EventBus.getDefault().post(WifiStateEvent(30, "已连接Wifi")) EventBus.getDefault().post(WifiStateEvent(30, "已连接Wifi"))
timeout({ TimerHelper.timeout({
state = State.INITED state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1)) EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000) }, 3000)
......
...@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit ...@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit
object TimerHelper { object TimerHelper {
val TAG = TimerHelper::class.java.simpleName private val TAG = TimerHelper::class.java.simpleName
private var mId: Long = 0L private var mId: Long = 0L
get() = ++field get() = ++field
......
...@@ -4,14 +4,14 @@ import android.util.Log; ...@@ -4,14 +4,14 @@ import android.util.Log;
import com.bgycc.smartcanteen.QRCodeEvent; import com.bgycc.smartcanteen.QRCodeEvent;
import com.bgycc.smartcanteen.action.*; import com.bgycc.smartcanteen.action.*;
import com.bgycc.smartcanteen.event.LogEvent; import com.bgycc.smartcanteen.event.LogEvent;
import com.bgycc.smartcanteen.helper.TimerHelper;
import com.bgycc.smartcanteen.server.websocket.MainWebSocket; import com.bgycc.smartcanteen.server.websocket.MainWebSocket;
import com.szxb.jni.libszxb; import com.szxb.jni.libszxb;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class QRCodeTask { public class QRCodeTask {
...@@ -31,7 +31,7 @@ public class QRCodeTask { ...@@ -31,7 +31,7 @@ public class QRCodeTask {
return sInstance; return sInstance;
} }
private ScheduledExecutorService mScanExec; private ScanAsyncTask mScanAsyncTask;
private QRCodeTask() {} private QRCodeTask() {}
...@@ -42,107 +42,101 @@ public class QRCodeTask { ...@@ -42,107 +42,101 @@ public class QRCodeTask {
public void start() { public void start() {
if (!support()) return; if (!support()) return;
if (mScanExec == null) { if (mScanAsyncTask == null) {
mScanExec = Executors.newSingleThreadScheduledExecutor(); mScanAsyncTask = new ScanAsyncTask();
mScanExec.scheduleAtFixedRate(new ScanRunnable(), 0, 200, TimeUnit.MILLISECONDS); TimerHelper.INSTANCE.loop(new Function2<Long, Boolean, Boolean>() {
@Override
public Boolean invoke(Long id, Boolean isLastTime) {
if (mScanAsyncTask == null) return false;
mScanAsyncTask.run();
return true;
}
}, 200, -1);
} }
} }
public void stop() { public void stop() {
if (mScanExec != null) { mScanAsyncTask = null;
mScanExec.shutdown();
mScanExec = null;
}
} }
private class ScanRunnable implements Runnable { private class ScanAsyncTask extends AsyncTask {
int lastLen = -1; int lastLen = -1;
byte[] lastBuf; byte[] lastBuf;
AsyncTask asyncTask = new AsyncTask() { @Override
@Override protected void run(int step, int progress) {
protected void run(int step, int progress) { // Log.i(TAG, String.format("step: %d progress: %d", step, progress));
// Log.i(TAG, String.format("step: %d progress: %d", step, progress)); switch (step) {
switch (step) { case 0:
case 0: if (progress != 0) break;
if (progress != 0) break;
byte[] buf = new byte[1024];
byte[] buf = new byte[1024]; int len = libszxb.getBarcode(buf);
int len = libszxb.getBarcode(buf);
boolean changed = checkBarCodeChanged(buf, len);
boolean changed = checkBarCodeChanged(buf, len); if (!changed || len <= 0) break;
if (!changed || len <= 0) break;
delay(1000);
delay(1000); String str = new String(buf, 0, len);
String str = new String(buf, 0, len); QRCodeEvent event = new QRCodeEvent(str.getBytes(), str, checkPayCodeType(str));
QRCodeEvent event = new QRCodeEvent(str.getBytes(), str, checkPayCodeType(str)); EventBus.getDefault().post(event);
EventBus.getDefault().post(event);
if (event.payCodeType == null) {
if (event.payCodeType == null) { parseCommand(event);
parseCommand(event); } else {
if (MainWebSocket.isConnected()) {
// if (false) {
nextProgress();
PayOnlineAction.getDefault().exec(event.string, event.payCodeType, new ActionResult() {
@Override
public void onSuccess(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
@Override
public void onFail(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
});
} else { } else {
if (MainWebSocket.isConnected()) { PayOfflineAction.getDefault().exec(event.string, event.payCodeType);
// if (false) { // PayOfflineAction.getDefault().upload();
nextProgress();
PayOnlineAction.getDefault().exec(event.string, event.payCodeType, new ActionResult() {
@Override
public void onSuccess(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
@Override
public void onFail(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
});
} else {
PayOfflineAction.getDefault().exec(event.string, event.payCodeType);
// PayOfflineAction.getDefault().upload();
}
} }
break; }
case 1: break;
break; case 1:
} break;
} }
}
boolean checkBarCodeChanged(byte[] buf, int len) { boolean checkBarCodeChanged(byte[] buf, int len) {
boolean changed = false; boolean changed = false;
if (len != lastLen) { if (len != lastLen) {
changed = true; changed = true;
} else if (lastBuf == null) { } else if (lastBuf == null) {
changed = true; changed = true;
} else { } else {
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
if (buf[i] != lastBuf[i]) { if (buf[i] != lastBuf[i]) {
changed = true; changed = true;
break; break;
}
} }
} }
lastLen = len;
lastBuf = buf;
return changed;
}
};
@Override
public void run() {
try {
asyncTask.run();
} catch (Exception e) {
Log.e(TAG, "ScanRunnable error");
e.printStackTrace();
} }
lastLen = len;
lastBuf = buf;
return changed;
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment