Android Asynctask、Runnable、timertask、Service

发布于 2024-10-05 07:50:45 字数 129 浏览 0 评论 0原文

这些方法(类)之间有什么区别?

我想运行一个每 5 秒运行一次的应用程序,当它完成时清除内存并且当 cpu 处于待机模式时,您可以运行该应用程序。这样应用程序就不会绑定到唤醒锁。

问候,

沙夫卡特

What are the differences between these methods (classes)?

I want to run a app that runs every 5 seconds, clear the memory when it is finished and when the cpu is in standby mode, that you can run the app. So that the app is not bound to a wakelock.

Regards,

Shafqat

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

命比纸薄 2024-10-12 07:50:45

前三个之间的区别只是为您完成的工作量。 Service 是一个 基本 Android 应用程序组件

AsyncTask 作为执行某些操作的便利类在新线程上工作,并在完成后使用调用它的线程(通常是 UI 线程)上的结果。它只是一个包装器,它使用几个可运行对象,但处理创建线程和处理线程之间消息传递的所有复杂问题。

可运行Runnable 接口应该由其实例旨在由线程执行的任何类实现。

TimerTask 是标准 Java 的一部分,可用于延迟或重复执行某些(可运行)代码。 不鼓励在 Android 上使用它。您可以使用处理程序来代替。

服务可以用作 Android 应用程序的独立且无 UI 的部分。它可以运行并创建自己的线程,并且可以通过 AlarmManager

它认为你想要的是一个创建它自己的线程并做一些工作的服务。当工作完成后,当垃圾收集器启动时,Android 上的内存将被释放,这是你无法控制的,这是一件好事。

AlarmManager 允许您以指定的时间间隔广播 Intent,甚至允许控制是否唤醒设备。您只需在您的服务中定义一个 BroadcastReceiver 并在您的清单中声明它。

我不太明白你问题的最后一部分,所以请进一步澄清你想要完成的任务。

The difference between first three is just the amount of work that has been done for you. And a Service is a fundamental Android application component.

AsyncTask as a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished. It's just a wrapper which uses a couple of runnables but handles all the intricacies of creating the thread and handling messaging between the threads.

The Runnable interface is at the core of Java threading. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

TimerTask is part of standard Java and can be use for delayed or repeated execution for some piece of (Runnable) code. It's use is discouraged on Android. You can use a Handler instead.

A Service can be used as a independent and UI-less part of your Android application. It can run and create it's own threads and can be started for UI or with Intents through a AlarmManager for example.

It think want you want is a Service which creates it's own thread and does some work. When the work is done, memory will be freed on Android when the garbage collector kicks in, something you do not control and that's a good thing.

The AlarmManager allows you to broadcast Intents at specified intervals and even allow control to wake-up the device or not. You just have to define a BroadcastReceiver in your Service and declare it in your manifest.

The last part of your question I don't really understand, so please clarify a bit more on what your trying to accomplish.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文