Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Last active September 10, 2018 14:44
Show Gist options
  • Save OrenBochman/ee419445243e0879d4c06806e04f72c4 to your computer and use it in GitHub Desktop.
Save OrenBochman/ee419445243e0879d4c06806e04f72c4 to your computer and use it in GitHub Desktop.
Treads Android

Threads - in Android

UI and Worker thread access

Android does not allow to access the UI from a worker tread.

This shows how to access the UI thread from a Worker thread. The following are some methods to access the UI.thread:

  • Activity.runOnUiThread(Runnable)
  • View.post(Runnable)
  • View.postDelayed(Runnable, long)

Cancelation

  • implement a canclation flag
  • exit run
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// a potentially time consuming task
final Bitmap bitmap = processBitMap("image.png");
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
}).start();
}
public class MyThread extends Thread {
private boolean mRunning;
@Override public void run() {
mRunning = true;
while (mRunning) {
// Do hard work...
}
}
public void cancel() {
mRunning = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment