-
-
Save anonymous/26dd9abf55c6f2c98d4df63c98d9671e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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