在Android服务中上载文件

在Android服务中上载文件,android,service,intentservice,Android,Service,Intentservice,让Android应用程序根据用户的请求将可能较大的文件上传到服务器的最佳方式是什么 我目前正在使用一个IntentService,在该服务中,我调用startForeground并定期更新通知进度,但该服务在大约一分钟后被系统随机终止 以下是OnHandleContent中的相关代码: class BeamService extends IntentService("SSH Beam") { override def onHandleIntent(intent: Intent) = {

让Android应用程序根据用户的请求将可能较大的文件上传到服务器的最佳方式是什么

我目前正在使用一个
IntentService
,在该服务中,我调用
startForeground
并定期更新通知进度,但该服务在大约一分钟后被系统随机终止

以下是
OnHandleContent
中的相关代码:

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
    方法。根据,如果要更新通知,必须再次使用
    startForeground
    。(这导致我的服务被系统终止)

  • startForeground
    中有一个命令,如果ID为0,它将不显示通知

  • 最后,我应该考虑一下,但给出了一个关于如何检查服务是否确实在前台的深入回答


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

使用startForeground有几个原因,但我想不出在IntentService上使用startForeground的理由!应该使用一个ItnService来在后台线程上执行长时间运行的任务,而不中断,从中需要持久结果。

您可以考虑为该服务发布代码。另外,请记住,
IntentService
有自己的后台线程(因此不要使用自己的线程),并且它不会让设备保持唤醒状态(请参见我的
wakefultintentservice
),我添加了
onHandleIntent
代码。有什么想法吗?我应该将服务放在一个单独的流程中,还是让它与启动它的活动保持在同一个流程中?“有什么想法吗?”--嗯,这不是Java代码,所以我不确定您在那里做什么。“我应该将服务放在一个单独的流程中,还是让它与启动它的活动保持在同一个流程中可以?”——将它放在同一个流程中应该可以。它在Scala中,所以或多或少是相同的,没有样板和括号。我没有从服务中得到任何类型的异常,只是在LogCat中“服务死亡”,然后是“计划重新启动”,所以我假设系统刚刚杀死了它,即使它在前台。是的,这不应该发生,特别是使用
startForeground()
。不知道你发生了什么事还有。。。这正是我想做的。如果我不使用“startForeground”,服务在下载的中途会被系统终止。回想起来,你可能是对的,尤其是关于无中断部分。我正试图找到一种方法,通过一个通知操作按钮在中途取消下载,根据文档,
IntentService
在处理下载之前不会收到另一个intent。据我所知,我可能可以使用一个
广播接收器
思想。嘿,“系统监视器”应用程序链接断开了!你能纠正一下吗?