【发布时间】:2013-06-24 04:02:46
【问题描述】:
让 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)
}
}
【问题讨论】:
-
您可以考虑发布该服务的代码。另外,请记住
IntentService有自己的后台线程(所以不要分叉你自己的),并且它不会让设备保持唤醒状态(请参阅我的WakefulIntentService了解相关内容)。 -
我添加了
onHandleIntent代码。有任何想法吗?我应该将服务放在单独的进程中,还是让它与启动它的活动保持在同一个进程中? -
“有什么想法吗?” ——嗯,嗯,那不是 Java 代码,所以我不确定你在做什么。 “我应该将服务放在一个单独的进程中,还是让它与启动它的活动保持在同一个进程中?” -- 在同一个进程中应该没问题。
-
它在 Scala 中,所以或多或少相同,没有样板和括号。我没有从服务中得到任何异常,只是在 LogCat 中“服务死亡”,然后是“计划重启”,所以我假设系统只是杀死了它,即使它在前台。
-
是的,这不应该发生,尤其是
startForeground()。不知道你发生了什么事。
标签: android service intentservice