2013-04-22 81 views
1

我現在正在製作一個應用程序,它可以隨機顯示一個數字時鐘onCreate。我想要的應用程序只是每分鐘重複一次該功能。有沒有人有任何想法如何實施?如何讓我的應用程序每分鐘重複一次該功能?

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    TextView textView = (TextView) findViewById(R.id.digitalClock1); 
    Random r = new Random(); 

    int x = r.nextInt(350 - 100); 
    int y = r.nextInt(800 - 100); 

    textView.setX(x); 
    textView.setY(y); 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

}

+0

使用異步任務在你的應用程序 – 2013-04-22 12:14:30

+0

更好地做任務的獨立功能,並調用它,無論你想 – 2013-04-22 12:15:50

回答

1

使用Handler

Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       Random r = new Random(); 

       int x = r.nextInt(350 - 100); 
       int y = r.nextInt(800 - 100); 

       textView.setX(x); 
       textView.setY(y); 
      } 
     }, 1000 * 60); 
+0

我一直斥罵,你不能從這個線程更新UI。人們說我需要使用AsyncTask。這是正確的嗎? – rebble 2013-04-22 13:22:00

+0

不,因爲這個Handler運行在UI Looper上 – 2013-04-22 14:32:31

+0

UI looper在哪裏? – rebble 2013-04-22 16:21:47

相關問題