执行重复的后台任务

时间:2014-03-21 05:32:21

标签: android

我需要一个关于我的应用程序的建议,有一个DB包含很多事件时间戳,以毫秒为单位。

现在,在AlarmManager的每一分钟间隔内,我从数据库中获取所需的毫秒数并显示通知。

这个任务是否有任何其他想法,我不需要在每一分钟内运行AlarmManager,如服务或任何其他想法。

我认为每隔一分钟使用一次AlarmManager就会耗费电量。

2 个答案:

答案 0 :(得分:1)

您可以使用TimerTask

可以找到示例here

[编辑] - 根据@Balaji_Kandasamy评论,包括必要部分

    // Create a Timer task
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            // Implement the task you want to perform periodically
        }
    };
    //create a new Timer
    Timer timer = new Timer();
    //specify the time interval in seconds after which task should run periodically
    int seconds = 60; // in your case as per question one minute
    //schedule your timer to execute perodically
    timer.schedule(task, seconds*1000);

最后(按钮点击或某事)在任务完成时取消计时器。

    timer.cancel();

[编辑] - 根据@Akhilesh_Mani评论,包括BOOT问题。

您可以为android.intent.action.BOOT_COMPLETED操作实施BroadcastReceiver

public class BootCompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, Intent intent) {
            //Perform Your opeartion to start a Service
            // In service execute the TimerTask
            // So that even if phone shut down your task
            // starts as boot completes
            // Start the same service when your application is launched
            // or installed for first time as you wish

        }

 }

清单输入:

<receiver android:name="com.example.BootCompleteReceiver " >
    <intent-filter>
        <category android:name="android.intent.category.DEFAULT" />

        <action android:name="android.intent.action.BOOT_COMPLETED" />

        <data android:scheme="package" />
    </intent-filter>
</receiver>

希望这会有所帮助。

答案 1 :(得分:1)

  1. 您可以创建后台粘性服务。
  2. 在该服务内部启动AsyncTask。
  3. 在AsyncTask的doInBackground中,您可以使用Thread.sleep(millis)。这将使它在那段时间停止。
  4. 当时间流逝时,在AsyncTask的onPostExecute中,您可以执行任何与UI相关的操作,最后创建AsyncTask的新实例并再次执行。
  5. 确保在ThreadPoolExecutor中运行AsyncTask,否则你不会在执行线程时实现并行性