嗨这是一个非常简单的问题,但我怀疑是一个复杂的答案:
它被称为“矿井情景”
让我解释一下:想象一个简单的场景,你必须制作一个应用程序,即使在没有信号的矿井下也可以https到网页。
即。如果没有连接,我如何尝试/排队提交事件(HTTPPOST),然后定期轮询队列(测试是否存在连接),直到事件可以触发。
PS:请注意:请问这是关于“如何”不是关于这个“错误”的对话,重新:同步或重复记录或覆盖2个用户的数据等等。
伪代码:
try{
MyHttpFileUploader myupload = new MyHttpFileUploader();
myupload.Start();
}
catch (InternetDownException ex){ //<-- how do I "throw" this in the start method gracefully?
GlobalQueue.Add(myupload); //<-- how do i set a timer properly that can action this queue (.Start() method) and post messages "when complete" to toast on the main ui thread but otherwise not block the ui whatsoever
}
答案 0 :(得分:2)
这是一个粗略的(因为我现在主要在c#中编码并且它与问题无关)半主题代码与主要点(线程)上的sun文档片段
创建一个类,可以访问扩展Thread的async post方法中所需的任何变量,即
class WorkerThread extends Thread {
int someDataYouNeed;
MyHttpFileUploader maybeAClassYouNeedToCommunicateWithAtEnd;
boolean hasNotFinishedTask = true;
WorkerThread(int someDataYouNeed, MyHttpFileUploader callBackClass) {
this.someDataYouNeed = someDataYouNeed;
this.maybeAClassYouNeedToCommunicateWithAtEnd = callBackClass;
}
public void run() {
while(hasNotFinishedTask){
//do your work in here
//Try contact network endpoint
try{
//do a network call and if it doesnt except
hasNotFinishedWork = false
//now callback to the class firing a method maybe (I just made one up)
maybeAClassYouNeedToCommunicateWithAtEnd.Close();
}catch(TheException ex){ //do nothing or log }
if(hasNotFinishedTask){
Thread.Sleep(60000);//retry every minute
}
}
}
}
//在异步任务失败时实例化线程....
WorkerThread worker = new WorkerThread(42, this);
worker.start();
正如我所说 - 我假设您的应用程序在智能手机上运行并且可以关闭...如果是这种情况并且只要操作系统允许它就可以保存状态(当您创建WorkerThread时) )如文件系统中的xml和WorkerThread实例化,检查文件是否存在,并从关闭时的位置开始。
关于a)即使我的例子是邮件服务器,它们都是可用的网络端点
更新:
现在我认为它将是直接的java(并记住我是c#所以通常不在平台上)但是看起来好像在较新版本的java中有这些东西的Async泛型类型的简单示例或者android ...
请参阅this blog post for android specific multi-threading或Google搜索针对特定平台示例的Android多线程
答案 1 :(得分:0)
一种方法是使用IntentService和AlarmManager来触发尝试发送数据。
此处有关于使用Intents here的更多信息,并且可以通过AlarmManager触发Intent
此线程上还有一些代码示例AlarmManager not working