Reputation: 7327
What is the best way of letting an Android app upload a potentially large file to a server at a request from the user?
I'm currently using an IntentService
, in which I call startForeground
and update the notification progress periodically, but the service randomly gets killed by the system after about a minute or so.
Here is the relevant code from 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)
}
}
Upvotes: 3
Views: 4064
Reputation: 8641
There are a few reasons to use startForeground, but I can't for the life of me think of a reason to use startForeground on an IntentService! An IntentService should be used to do long-running tasks on a background thread, without interruption, from which you want persistent results.
Upvotes: 0
Reputation: 7327
I found out how to implement that properly :
Do not use the notify
method from the NotificationManager
while you are in foreground. According to this, you have to use startForeground
again if you want to update the notification. (This was causing my service to get killed by the system)
There's a weird quirk in startForeground
that makes it not show notifications if the ID is 0.
Finally, I should have thought about it, but this question gives a nice in-depth answer on how to check if the service is indeed in foreground.
(The fantastic flying network monitor from the System Monitor app also helped me a lot to check if the upload was still running while I was starting other apps to try and trigger the "service died" message)
Upvotes: 1