【发布时间】:2014-03-19 11:09:37
【问题描述】:
我想创建一个小应用程序,它应该将一些 JSON 数据发送到远程服务器。
我需要处理诸如用户没有互联网或无法发送数据等情况,因此手机会重试,直到该数据已从手机发送并被服务器接收。
有这样的模式吗?通用模式还是特定于 Android?
提前非常感谢!
【问题讨论】:
我想创建一个小应用程序,它应该将一些 JSON 数据发送到远程服务器。
我需要处理诸如用户没有互联网或无法发送数据等情况,因此手机会重试,直到该数据已从手机发送并被服务器接收。
有这样的模式吗?通用模式还是特定于 Android?
提前非常感谢!
【问题讨论】:
我正在使用超时时间戳来了解是否未发送消息(在本例中是用于串行通信):
private TimerTask WriterTask = new TimerTask() {
@Override
public void run() {
wasStarted = true;
synchronized (MessageQueue) {
if (mSIOManager != null && mSIOManager.getmWriteBufferSize() == 0
&& MessageQueue.size() > 0) {
QueueEntry item = MessageQueue.peek();
if (item != null && !item.sent) {
timeoutTimer = System.currentTimeMillis();
mSIOManager.writeAsync(item.Msg.getBytes());
Log.v(TAG, HexDump.dumpHexString(item.Msg.getBytes())
+ " - Written to Buffer");
item.sent = true;
}
}
try {
if (System.currentTimeMillis() - timeoutTimer > TIMEOUT && MessageQueue.peek().sent) {
Log.i(TAG, "Message timed out: " + HexDump.dumpHexString(MessageQueue.poll().Msg.getBytes()));
}
} catch (NullPointerException e) {
// Queue empty
}
}
}
};
因此,您可以从 ie 增加任务的调度率,而不是记录事件。 100 到 10000 毫秒
Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(WriterTask,100L,10000L);
如果您的数据最终被发送,您只需取消计划
mTimer.cancel();
【讨论】: