0
我需要在一個時間間隔內收集數據,這裏的數據收集是用計數整數模擬的。我似乎無法收集該整數,但。我需要集合在單擊按鈕後啓動,並在單擊另一個時結束。有任何想法嗎?如何在Android中使用計時器?
package com.example.test.gothedistance;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
Button start, stop;
TextView sumText;
int count;
Timer t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById((R.id.stopButton));
sumText = (TextView) findViewById(R.id.sumTV);
t = new Timer();
count = 0;
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
count++;
}
},0,2000);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
t.cancel();
sumText.setText(count);
}
});
}
}
我認爲您正在尋找類似以下的內容:http://android-er.blogspot.com.es/2013/12/example-of- using-timer-and-timertask-on.html希望它有幫助! –
我也會說,定時器通常不會在Android中使用,通常是它的警報或處理程序的延遲消息。 –