【问题标题】:Android: how to run AsyncTask at regular interval in background serviceAndroid:如何在后台服务中定期运行 AsyncTask
【发布时间】:2014-05-12 04:42:38
【问题描述】:

如何在后台服务中以 2 分钟的固定间隔运行 AsyncTask 睡眠 10 次?

随着 VM 随时停止我的服务,我的 AsyncTask 也将关闭。

我尝试过ScheduledThreadPoolExecutorTimerTimerTask,一旦Service 停止,所有这些都会停止。

有什么好的选择吗?

感谢任何帮助。

【问题讨论】:

  • @Nisha,需要任何信息吗?我需要定期在后台运行 AsyncTask。我猜你知道服务会随时停止VM。

标签: android android-asynctask android-service


【解决方案1】:

您的服务永远不会停止,但您应该显示通知。尝试实现前台服务。 foreground service

前台服务显示通知并且从不停止。

在您的服务中实现此代码 sn-p

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);

【讨论】:

  • 谢谢,有没有其他不显示通知状态栏的方法?
  • 如果不显示通知,您的服务将在 android 认为需要资源时被终止。
【解决方案2】:

你试过处理程序吗?你可以在link中阅读更多相关信息

【讨论】:

  • 谢谢,快速提问,Handler 是否与 Service 一起关闭。 Service 将被 VM 杀死以获取资源。即使应用程序没有启动,我也需要在后台运行AsyncTask。所以基本上我选择了Service。我的实现工作,当Service 没有被关闭,但不幸的是Service 被VM 关闭。
猜你喜欢
  • 2023-03-22
  • 2017-07-01
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 2014-04-11
相关资源
最近更新 更多