gpt4 book ai didi

android - 在 Activity 和服务之间共享数据库

转载 作者:太空狗 更新时间:2023-10-29 16:07:15 24 4
gpt4 key购买 nike

我正在创建一个排队的上传管理器。用this回答我之前问题的指导,我将使用服务来上传这些图像。建议我使用数据库来跟踪成功上传的文件和待处理的文件。

我最初的研究让我相信我会想要创建一个绑定(bind)服务,这样我就可以在照片上传后更新我的 UI,以及一个启动服务,这样它就可以独立于我创建的 Activity 运行它。看来我还需要通过应用程序 list 中的 process=":something" 指令在自己的进程中启动它。

我的问题是,在 N 个 Activity 客户端和 uploader 服务之间共享 SQLite(除非有更好的方法)数据库的最佳方式是什么?

我设想它以伪代码的形式工作:

// in an app
writeRecordToDb( . . . );

// start service
if( service doesn't exist )
{
// start service, and bind
}

// in the service:
if( shared db has another row )
{
doDownload( . . . );

if( download worked )
{
notifyActivity();

if( db has another row )
doDownload( . . . );
}
else
{
retryDownload( . . . );
}
}

这是解决此问题的正确方法吗?我再次尝试规避在几乎没有或没有蜂窝信号时让多个 Activity 实例请求上传照片的问题。我刚刚读完服务和绑定(bind)服务文档,感觉不错,但不是很好。

最佳答案

My initial research leads me to believe that I'll want to create a Bound Service

我不会。

so I can update my UI once the photos have uploaded

您不需要使用绑定(bind)模式来更新 UI。您可以:

  • 使用 Activity 获取的 LocalBroadcastManager 发送本地广播,或者
  • 调用 Activity 在 startActivity() 上的 Intent extra 中提供的 PendingIntent,或
  • 给 Square 的 Otto event bus试试看(看起来很有趣,但我还没用过)

as well as a Started Service, so it can run independent of my Activities that create it

这就是为什么你不应该为绑定(bind)而烦恼,因为你不需要它,但你确实需要启动服务。

My question is, what would the best way of sharing an SQLite (unless there is a better way) database amongst the N activity clients and the uploader service?

选项 #1:将您的 SQLiteOpenHelper 保存在静态数据成员中

选项 #2:在数据库周围使用 ContentProvider 包装器

Is this the correct way to go about this?

使用数据库作为组件之间的通信 channel 类似于两个隔壁邻居使用双翼飞机拖曳的横幅相互通信。是的,它有效。然而,它速度慢且昂贵。

(另外,当你需要双翼飞机时,从来没有双翼飞机,但我离题了......)

如果您希望使用数据库作为待处理下载的后备存储,以防发生某些中断(例如,用户关闭设备)并且您希望稍后继续下载这些内容,这很好。但是,该服务将根据您通过 startService() 发送给它的命令知道要下载什么。

关于android - 在 Activity 和服务之间共享数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11352625/

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