每秒运行循环java

时间:2012-07-27 11:38:38

标签: java android

int delay = 1000; // delay for 1 sec. 
int period = 10000; // repeat every 10 sec. 
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() 
    { 
        public void run() 
        { 
            displayData();  // display the data
        } 
    }, delay, period);  

其他:

while(needToDisplayData)
{
    displayData(); // display the data
    Thread.sleep(10000); // sleep for 10 seconds
}   

它们都不起作用(应用程序强制关闭)。我可以尝试哪些其他选择?

5 个答案:

答案 0 :(得分:27)

您的代码失败,因为您在后台线程中执行睡眠,但必须在UI线程中执行显示数据。

您必须从runOnUiThread(Runnable)运行displayData或定义处理程序并向其发送消息。

例如:

(new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                while (!Thread.interrupted())
                    try
                    {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() // start actions in UI thread
                        {

                            @Override
                            public void run()
                            {
                                displayData(); // this action have to be in UI thread
                            }
                        });
                    }
                    catch (InterruptedException e)
                    {
                        // ooops
                    }
            }
        })).start(); // the while thread will start in BG thread

答案 1 :(得分:8)

使用从ViewHandler访问的onPostDelayed()。您可以通过不创建Timer或新Thread来节省内存。

private final Handler mHandler = new Handler();

private final Runnable mUpdateUI = new Runnable() {
    public void run() {
        displayData();
        mHandler.postDelayed(mUpdateUI, 1000); // 1 second
        }
    }
};

mHandler.post(mUpdateUI);

答案 2 :(得分:1)

试试这个:

@Override                    
    public void run() {   
            TextView tv1 = (TextView) findViewById(R.id.tv);
            while(true){
               showTime(tv1);                                                                
               try {
                   Thread.sleep(1000);
               }catch (Exception e) {
                   tv1.setText(e.toString());
               }           
            } 
    }       

你也可以尝试这个

还有另一种方法可用于在特定时间间隔更新UI。以上两个选项是正确的,但取决于您可以使用其他方式在特定时间间隔更新UI的情况。

首先为Handler声明一个全局变量,以便从Thread更新UI控件,如下所示

处理程序mHandler = new Handler(); 现在创建一个Thread并使用while循环来定期使用线程的sleep方法执行任务。

new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(10000);
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            // Write your code here to update the UI.
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }).start();

答案 3 :(得分:0)

你犯了几个错误:

  1. 你永远不应该在主线程上调用Thread.sleep()(你也不应该长时间阻塞它)。一旦主线程被阻塞超过5秒,ANR(应用程序没有响应)就会发生并且强制关闭。

  2. 你应该避免在android中使用Timer。请尝试使用Handler。处理程序的好处是它是在主线程上创建的 - >可以访问视图(与Timer不同,它在自己的线程上执行,无法访问视图)。

    class MyActivity extends Activity {
    
        private static final int DISPLAY_DATA = 1;
        // this handler will receive a delayed message
        private Handler mHandler = new Handler() {
            @Override
            void handleMessage(Message msg) {
                if (msg.what == DISPLAY_DATA) displayData();
            }
         };
    
         @Override
         void onCreate(Bundle b) {
             //this will post a message to the mHandler, which mHandler will get
             //after 5 seconds
             mHandler.postEmptyMessageDelayed(DISPLAY_DATA, 5000);
         }
     } 
    

答案 4 :(得分:0)

当我试图解决您无法在Android的DigitalClock小部件中隐藏秒数的问题时,我遇到了这个帖子。 DigitalClock现已弃用,现在使用的推荐小部件是TextClock。那不适用于旧的API ......所以我必须写自己的24小时制。我不知道这是否是一个很好的实现,但它似乎工作(并且它每秒更新):

    import java.util.Calendar;

    import android.os.Handler;
    import android.view.View;
    import android.widget.TextView;


    /**
     * A 24 hour digital clock represented by a TextView
     * that can be updated each second. Reads the current
     * wall clock time.
     */
    public class DigitalClock24h {

            private TextView mClockTextView; // The textview representing the 24h clock
            private boolean mShouldRun = false; // If the Runnable should keep on running

            private final Handler mHandler = new Handler();

            // This runnable will schedule itself to run at 1 second intervals
            // if mShouldRun is set true.
            private final Runnable mUpdateClock = new Runnable() {
                    public void run() {
                            if(mShouldRun) {
                                    updateClockDisplay(); // Call the method to actually update the clock
                                    mHandler.postDelayed(mUpdateClock, 1000); // 1 second
                            }
                    }
            };


            /**
             * Creates a 24h Digital Clock given a TextView.
             * @param clockTextView
             */
            public DigitalClock24h(View clockTextView) {
                    mClockTextView = (TextView) clockTextView;
            }

            /**
             * Start updating the clock every second.
             * Don't forget to call stopUpdater() when you
             * don't need to update the clock anymore.
             */
            public void startUpdater() {
                    mShouldRun = true;
                    mHandler.post(mUpdateClock);
            }

            /**
             * Stop updating the clock.
             */
            public void stopUpdater() {
                    mShouldRun = false;
            }


            /**
             * Update the textview associated with this
             * digital clock.
             */
            private void updateClockDisplay() {

                    Calendar c = Calendar.getInstance();
                    int hour = c.get(Calendar.HOUR_OF_DAY); // 24 hour
                    int min = c.get(Calendar.MINUTE); 

                    String sHour;
                    String sMin;

                    if(hour < 10) {
                            sHour = "0" + hour;
                    } else sHour = "" + hour;

                    if(min < 10) {
                            sMin = "0" + min;
                    } else sMin = "" + min;

                    mClockTextView.setText(sHour + ":" + sMin);
            }

    }

谢谢biegleux指出我,我想,正确的方向!