在Android的计划任务 [英] Schedule task in android

查看:92
本文介绍了在Android的计划任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用跌破$ C $下计划任务的机器人,但它不给任何结果。请告知是一样的。

  INT延迟= 5000; //延迟5秒。
INT周期= 1000; //重复每个秒。
定时器定时=新的Timer();
timer.scheduleAtFixedRate(新的TimerTask(){

   公共无效的run(){
      Toast.makeText(getApplicationContext(),快跑!,Toast.LENGTH_SHORT).show();
   }

},延迟,周期);
 

解决方案

TimerTasks不理想在Android环境中使用,因为它们不是上下文感知。如果你的环境消失了,一个TimerTask仍然会耐心等待的背景下,最终烧制并可能崩溃您的应用程序,因为它的活动是previously完成。或者,它可能会继续引用在你的活动,它已经关闭之后,$ P $被垃圾收集,并有可能使您的应用程序运行的内存pventing吧。

相反,使用postDelayed()中,当活动被关闭,这将自动地取消该任务。

 最终诠释延迟= 5000;
最终诠释周期= 1000;
最终的可运行R =新的Runnable(){
    公共无效的run(){
        Toast.makeText(getApplicationContext(),快跑!,Toast.LENGTH_SHORT).show();
        postDelayed(这一点,周期);
    }
};

postDelayed(R,延迟);
 

顺便说一句,如果你需要手动取消你的任务,你可以使用 removeCallbacks(R) r是你贴previously可运行。

I am using below code for scheduling a task in android but its not giving any results. Please advise on the same.

int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

   public void run() {
      Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show();
   }

}, delay, period);

解决方案

TimerTasks are not ideal to use in an android environment because they're not context-aware. If your context goes away, the TimerTask will still wait patiently in the background, eventually firing and potentially crashing your app because its activity was previously finished. Or, it may keep references to your activity around after it's been closed, preventing it from being garbage collected and potentially making your app run out of memory.

Instead, use postDelayed(), which will automatically cancel the task when the activity is shut down.

final int delay = 5000;
final int period = 1000;
final Runnable r = new Runnable() {
    public void run() {
        Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show();
        postDelayed(this, period);
    }
};

postDelayed(r, delay);

By the way, if you ever need to cancel your task manually, you can use removeCallbacks(r) where r is the runnable you posted previously.

这篇关于在Android的计划任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆