android - 在 Android 服务中上传文件

标签 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)
  }
}

最佳答案

我发现了如何正确地实现它:

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

  • 有一个 weird quirkstartForeground 中,如果 ID 为 0,它显示通知。

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

(来自 System Monitor 应用程序的出色的飞行网络监视器也帮助我检查上传是否仍在运行,同时我正在启动其他应用程序以尝试触发“服务已终止”消息)

关于android - 在 Android 服务中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17329835/

相关文章:

android - 可以用android手机当pc来写c,lisp,java.....并编译代码运行吗?

c# - 套接字 - Android 客户端到 C# 服务器的连接

Android PDF 未在浏览器和 WebView 中加载

android - 辅助功能服务未在服务中列出?

android - 在 Android Intent 服务中使用 Parse.com

android - 如何在 IntentService 中使用 WebView?

android - react native : This release is not compliant with the Google Play 64-bit requirement

c++ - 使用QT开发服务器应用程序是个好主意吗?(QT5)

android - 手动结束 IntentService 工作线程

php - MySQL服务没有自动启动