while (startTime < endTime)
First problem: you're comparing two fixed values, which are initialized once and then never change.
You're going to want to replace
startTime
with
System.currentTimeMillis()
.
btn.setOnClickListener(new View.OnClickListener() ...
Second problem: you're never asking the code to terminate. Instead, you're adding a new "click" handler over and over again in a tight loop.
A simple solution would be to add the handler once, and check the time limit within the
onClick
method:
private TextView t1;
private Button btn;
private int count = 0;
private long endTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endTime = System.currentTimeMillis() + 20000;
t1 = (TextView)findViewById(R.id.textView);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (System.currentTimeMillis() < endTime) {
count = count + 1;
t1.setText(Integer.toString(count));
}
}
});
}