Skip to content

Instantly share code, notes, and snippets.

Created February 3, 2017 02:59
Show Gist options
  • Save anonymous/26dd9abf55c6f2c98d4df63c98d9671e to your computer and use it in GitHub Desktop.
Save anonymous/26dd9abf55c6f2c98d4df63c98d9671e to your computer and use it in GitHub Desktop.
public class MainActivity extends AppCompatActivity {
TextView tv;
Button startBt, stopBt;
UpdateTask tvCounter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView);
startBt = (Button)findViewById(R.id.button);
stopBt = (Button)findViewById(R.id.button2);
tvCounter = new UpdateTask(tv);
}
public void startClick(View view){
tvCounter = new UpdateTask(tv);
tvCounter.execute();
}
public void stopClick(View view){
tvCounter.cancel(true);
CharSequence text = "Hello toast!";
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}
class UpdateTask extends AsyncTask<Void, Integer, Void> {
TextView timeTv;
public UpdateTask(TextView timeTv){
this.timeTv = timeTv;
}
protected void onProgressUpdate(Integer... args) {
int counter = args[0];
timeTv.setText("" + counter);
}
@Override
protected Void doInBackground(Void... params) {
int counter = 0;
while(!isCancelled()) {
counter++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(counter); // This will call onProgressUpdate
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment