i am creating media recorder demo application. for that i have take two button start and stop.
i want to display t开发者_JAVA百科imer when click on start button and want to stop on stop button.any idea?
Thanks
Simple solution can be based on these classes:
public static class TimeCounter{
private long startTime;
public TimeCounter(){
startTime = new Date().getTime();
}
public long countTime(){
return new Date().getTime() - startTime;
}
}
public class TimeCounterTask extends AsyncTask<TimeCounter, Long, Void>{
@Override
protected Void doInBackground(TimeCounter... params) {
TimeCounter tc = params[0];
while(true){
publishProgress(new Long(tc.countTime()));
try{
Thread.sleep(500);
} catch(InterruptedException e){
break;
}
}
return null;
}
@Override
protected void onProgressUpdate(Long... values) {
super.onProgressUpdate(values);
long millis = values[0].longValue();
int minutes = (int) ((millis / 1000) / 60);
int seconds = (int) ((millis / 1000) % 60);
String s = String.format("%d min, %d sec",
minutes, seconds);
timerText.setText(s);
}
}
- in start button handler create new TimerCounterTask and execute it this new TimerCounter() parameter
- in stop button handler stop current task
- timerText is TextView for display timer
精彩评论