让 Android 应用应用户请求将可能较大的文件上传到服务器的最佳方式是什么?
我目前正在使用 IntentService
,我在其中调用 startForeground
并定期更新通知进度,但该服务在大约一分钟后被系统随机终止左右。
这是来自 onHandleIntent
的相关代码:
class BeamService extends IntentService("SSH Beam") {
override def onHandleIntent(intent: Intent) = {
...
// Start the notification
startForeground(0,
builder
.setTicker("Starting transfer")
.setContentTitle(filename)
.setContentText("Starting transfer")
.setOngoing(true).build
)
// Create the session and the monitor
val session = server.createSession(auth)
implicit val monitor = Monitor(filename, size)
// Send the file
try {
session.connect
session.cd(destination)
session.put(filename, is)
} catch {
case e: Throwable => {
notificationManager.notify(0,
builder.setProgress(0, 0, false)
.setTicker("Transfer failed")
.setContentText(e.getMessage)
.build
)
e.printStackTrace
}
} finally {
session.disconnect
is.close
}
stopForeground(false)
}
}
最佳答案
我发现了如何正确地实现它:
当您在前台时,不要使用
NotificationManager
中的notify
方法。根据this ,如果你想更新通知,你必须再次使用startForeground
。 (这导致我的服务被系统杀死)有一个 weird quirk在
startForeground
中,如果 ID 为 0,它不显示通知。最后,我应该考虑一下,但是this question就如何检查服务是否确实在前台提供了一个很好的深入答案。
(来自 System Monitor 应用程序的出色的飞行网络监视器也帮助我检查上传是否仍在运行,同时我正在启动其他应用程序以尝试触发“服务已终止”消息)
关于android - 在 Android 服务中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17329835/