【问题标题】:writing a background program that executes when the main application is closed in android编写一个在android中关闭主应用程序时执行的后台程序
【发布时间】:2012-03-25 17:53:25
【问题描述】:

我正在编写一个 android 应用程序,当用户登录到应用程序时,它会与服务器通信。现在,如果用户在未注销的情况下关闭应用程序,我想每 15 分钟查询一次服务器,以查看特定用户是否收到任何更新。如果是,那么我想在单击用户直接进入显示更新的应用程序活动时推送通知。

这如何在android中实现?有可能吗?
谁能建议使用计时器的解决方案?请记住,这个后台程序只能在实际应用程序关闭时运行。

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以为此目的使用服务。看看这个: http://developer.android.com/guide/topics/fundamentals/services.html http://marakana.com/forums/android/examples/60.html http://developer.android.com/guide/topics/ui/notifiers/notifications.html

    【讨论】:

    • 即使应用程序本身关闭,服务也会运行吗?
    • 是的。服务通常用于在后台进行这种长时间运行的操作。如果您停止应用程序,您的服务将继续工作。服务可以自行停止,也可以由系统或启动该服务的应用程序停止。
    【解决方案2】:

    是的,这是可能的。

    我会做以下事情:

    1. AlarmManagersetRepeating 一起使用。这将为您提供 15 分钟的间隔。

    2. setRepeating 中,为IntentService 子类传入PendingIntent

    3. 在您的IntentService 子类中,在handleIntent 中,查询您的服务器,然后创建一个Notification,如http://developer.android.com/guide/topics/ui/notifiers/notifications.html 中所述

    4. Notification 将包含另一个PendingIntent,它将把用户带回您的应用程序。请务必指定包含与该更新相关的 UI 的 Activity

    您可以在 http://developer.android.com/guide/topics/fundamentals/services.html 的服务指南中了解有关 IntentServices 的更多信息

    您可以通过http://developer.android.com/reference/android/app/AlarmManager.html了解更多关于AlarmManager的信息

    【讨论】:

    • 应用程序本身关闭时,Intent 服务还会运行吗?
    • AlarmManager 将启动您的IntentService,即使没有可见的活动。这在developer.android.com/reference/android/app/AlarmManager.html 中有详细记录
    • 感谢您的回答。您能否也请指出一些教程或一些描述使用警报管理器调用意图服务的示例?
    • 不客气。您可以在其中找到一些说明这一点的代码的地方是stackoverflow.com/questions/3859489/… 的答案
    • 请多多包涵。我还有一个问题要问你。为什么您建议我为 Intent Service 传递待处理的 Intent?同样的事情可以在报警管理器调用的广播接收器的 onreceive() 函数中完成。使用服务(Intent Service)有什么好处?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多