上传Android服务中的文件

时间:2013-06-26 20:28:08

标签: android service intentservice

让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)
  }
}

2 个答案:

答案 0 :(得分:1)

我发现了如何正确实现:

  • 当您在前台时,使用notify中的NotificationManager方法。根据{{​​3}},如果要更新通知,则必须再次使用startForeground(这导致我的服务被系统杀死)

  • startForeground中有一个this,如果ID为0,则 显示通知。

  • 最后,我应该考虑一下,但是weird quirk给出了一个很好的深入答案,就如何检查服务是否确实在前台。

(来自this question应用程序的神奇飞行网络监视器也帮助我检查上传是否仍在运行,而我正在启动其他应用程序以尝试触发“服务已死”消息)

答案 1 :(得分:0)

使用startForeground有几个原因,但我不能为我的生活想到在IntentService上使用startForeground的原因!应该使用IntentService在后台线程上执行长时间运行的任务,而不会中断,从而需要持久的结果。