我如何制作Android应用程序,每X秒做一些事情

时间:2010-09-29 14:36:53

标签: android multithreading action

您好我想做每1秒呼叫功能或做其他事情的apliacation。 我有这个代码不能正常你能说出什么问题吗?

public class App5_Thread extends Activity implements Runnable {    
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                Thread thread = new Thread(this);    
                thread.start();
        }
        @Override                    
        public void run() {                
                TextView tv1 = (TextView) findViewById(R.id.tv);
                showTime(tv1);                                                                
                try {
                    Thread.sleep(1000);
                }catch (Exception e) {
                    tv1.setText(e.toString());
                }            
        } 
        public void showTime(TextView tv1 ){                
            String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
            tv1.setText(sdf.format(cal.getTime())+" "+System.currentTimeMillis());                    
        }           

}

4 个答案:

答案 0 :(得分:6)

你在run()函数中没有循环,尝试改变它:

    @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执行更改,可以通过以下示例完成:

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

答案 1 :(得分:3)

就像我之前说过的那样,你必须在UI线程(创建组件的线程)中修改textView。

为了做到这一点,请使用Handler,如下所示: (不要在你的线程中循环,只是将消息发布到处理程序)

private TextView tv1;  

Handler tick_Handler = new Handler();
MyThread tick_thread = new MyThread();

private class MyThread implements Runnable {
    public void run() {
            String txt = "Vlakno id:" + Thread.currentThread().getId()+" THREAD";
            Log.v("MyActivity", txt);  
            //tv1.setText(txt);
            showTime(tv1);
            tick_Handler.postDelayed(tick_thread, 1000);
    }
}    

String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";   
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);

private void showTime(TextView tv ){      
 Calendar cal = Calendar.getInstance();  
 tv.setText(sdf.format(cal.getTime())+" "+System.currentTimeMillis());  
}


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv1 = (TextView) findViewById(R.id.tv);

    tick_Handler.post(tick_thread);
}

顺便说一句,如果你想要一个准确的计时器,你应该每隔300毫秒勾选一次。如果你每秒都执行一次“showtime”方法,你可能会看到一些奇怪的秒。

答案 2 :(得分:1)

这里似乎有两个问题。

1 - 如果您的线程中没有循环,“showtime”方法将只调用一次。

2 - 从与主线程不同的线程修改UI组件将失败。

你应该在这里找到你想要的东西: http://developer.android.com/resources/articles/timed-ui-updates.html

答案 3 :(得分:0)

我已按照

更改了代码

所有这些方法都有3种工作方式(显示日志输出)。

但TextView没有更新。为什么?

package cz.cvut.fel.android;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class App5_RepeatedAction extends Activity {

    static TextView tv1;    
    static class MyThread implements Runnable {
        public void run() {
            boolean end = false;
            while (!end) {
                String txt = "Vlakno id:" + Thread.currentThread().getId()+" THREAD";
                Log.v("MyActivity", txt);  
                //tv1.setText(txt);
                showTime(tv1);
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    System.err.println(ex.toString());
                }
            }
        }
    }    
    static void showTime(TextView tv1 ){                
        String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        tv1.setText(sdf.format(cal.getTime())+" "+System.currentTimeMillis());                    
    }
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv1 = (TextView) findViewById(R.id.tv);
        //----------ScheduledExecutorService
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                String txt = "ScheduledExecutorService";
                Log.v("MyActivity", txt);  
                //tv1.setText(txt);
                showTime(tv1);
            }
        }, 0, 5, TimeUnit.SECONDS);

        //----------TIMER
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                String txt = "Timer";
                Log.v("MyActivity", txt);  
                //tv1.setText(txt);
                showTime(tv1);
            }
        }, 0, 1000);
        //-----------THREAD
        try {
            boolean quit = false;           
            Thread t = new Thread(new MyThread());
            //t.setDaemon(true);
            t.start();            
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
}