处理程序或计时器android

时间:2011-12-30 10:50:03

标签: java android timer handler

我试着每1分钟显示一次消息!不停!我发现在固定延迟后只显示一次msg的例子!你能帮忙怎么设置它?或者如果使用计时器是更好的工作方式,我需要一个例子!

public class TimertestActivity extends Activity {
    /** Called when the activity is first created. */

      @Override   
      public void onCreate(Bundle icicle) {   
        super.onCreate(icicle);   
        setContentView(R.layout.main);  
        Handler handler = new Handler();
        handler.postDelayed(
            new Runnable() {
                public void run() {
                    afficher();
                }
            }, 1000L);

      }   

      public void afficher()
      {
          Toast.makeText(getBaseContext(),
                     "test",
                     Toast.LENGTH_SHORT).show();
      }
}

谢谢!

3 个答案:

答案 0 :(得分:24)

试试这段代码 -

public class TimertestActivity extends Activity {
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            afficher();
        }
    };

    /** Called when the activity is first created. */

      @Override   
      public void onCreate(Bundle icicle) {   
        super.onCreate(icicle);   
        setContentView(R.layout.main);  
        runnable.run();
      }   

      public void afficher()
      {
          Toast.makeText(getBaseContext(),
                     "test",
                     Toast.LENGTH_SHORT).show();
          handler.postDelayed(runnable, 1000);
      }
}

答案 1 :(得分:2)

exec 9 <> program.fifo

}

答案 2 :(得分:1)

您可以使用TimerTask。但是当您的设备进入睡眠状态时,它将无法运行,因此我认为您可以使用AlarmManager。 无论如何,请TimerTask提及AlarmManager am = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), interval, pendingIntent);

AlarmManager代码,

{{1}}