gpt4 book ai didi

java - Android:排队发布直到有连接

转载 作者:太空狗 更新时间:2023-10-29 13:32:47 24 4
gpt4 key购买 nike

嗨,这是一个非常简单的问题,但我怀疑答案很复杂:

这叫做“矿井场景”

让我解释一下:想象一个简单的场景,您必须制作一个应用程序,即使在没有信号的矿井下也可以 httppost 到网页。

即如果没有连接,我如何尝试/排队提交事件 (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
}

最佳答案

这是一个粗略的(因为我现在主要用 c# 编写代码,它与问题无关)半伪代码,主要点(线程)上有 sun 文档 fragment

创建一个类,该类可以访问扩展 Thread 的异步 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 中有这些东西的异步泛型类型的简单示例或者安卓...

参见 this blog post for android specific multi-threading或在谷歌上搜索 Android 多线程以获取特定于平台的示例

关于java - Android:排队发布直到有连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13723157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com