Android regular task (cronjob equivalent)

倾然丶 夕夏残阳落幕 提交于 2019-12-17 16:19:58

问题


The last time this question was asked (by a different user), the answer response was:

If this is in a running activity, you could use Timer/TimerTask and a Handler, or you could use postDelayed() and an AsyncTask.

Here: Android Repetitive Task

I am still learning how to program android. I have gone through the skills I do know including threads and had many issues with my code. Can anyone give an example of how to use: time/timertask and handler OR postDelayed() and AsyncTask.

Thanks in advance :)


回答1:


I have a feeling this may help: http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html




回答2:


For Cron like tasks you have to use AlarmManager, this is a system service, for using it in your code you need to call:

AlarmManager myAlarmManager = Context.getSystemService(Context.ALARM_SERVICE).

Full docs about AlarmManager here.




回答3:


The most suitable approach is through services. I learned how to write services by looking at the source code for the stock Email app that is included with Android.

The general idea is that you override the Service class, and set up alarms to activate your service. Unlike daemons and Windows services, Android services aren't always running - they start up (usually when activated by an alarm), perform work, then shut down. In some cases, you may need to acquire a partial wake lock to keep the service going until it completes the task - otherwise, Android may kill your service prematurely.




回答4:


If you want to build a cronjob runner then what you want is a Service:

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.




回答5:


The reference from google is actually quite good.

http://developer.android.com/reference/android/os/AsyncTask.html



来源:https://stackoverflow.com/questions/5266878/android-regular-task-cronjob-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!