我正在使用Eclipse for Android.我试图做一个简短的重复计时器,有一个短暂的延迟.它将在单击TextView timerTV后启动.此代码位于onCreate方法中:
timerTV = (TextView) findViewById(R.id.timerTV);
timerTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Timer gameTimer = new Timer();
TimerTask doThis;
int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
doThis = new TimerTask() {
public void run() {
Toast.makeText(getApplicationContext(), "timer is running", Toast.LENGTH_SHORT).show();
}
};
gameTimer.scheduleAtFixedRate(doThis, delay, period);
Run Code Online (Sandbox Code Playgroud)
每当我尝试运行它时,弹出一个"类文件编辑器",错误:"找不到源"JAR文件C:\ Program Files\Android\android-sdk\platforms\android-8\android.jar没有来源附件.您可以通过单击下面的附加源附加源:[附加源...]当我单击此按钮时,Eclipse要求我选择包含'android.jar'的位置文件夹我试图这样做,但无法一直导航到无论如何它所在的文件夹.
我认为这个问题出现在我的代码中.我一直在搜索几个小时,甚至多次复制和粘贴代码.
将实际的Timer(java.util.Timer)与runOnUiThread()结合使用是解决此问题的一种方法,下面是如何实现它的示例.
public class myActivity extends Activity {
private Timer myTimer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
Run Code Online (Sandbox Code Playgroud)
消息来源:http://steve.odyfamily.com/? p = 12
| 归档时间: |
|
| 查看次数: |
17457 次 |
| 最近记录: |