Posts Tagged ‘ Thread ’

Android Simple Progress Dialog implementation

Add a progress dialog very simply into your code.

private ProgressDialog mDialog;
mDialog = new ProgressDialog(this); // This being a context, could try getBaseContext() as well

Then, say you want it to show up on a button press. In the buttons listener, put this in (you can adjust the variable numbers later after it works)

mDialog.setMessage("Gathering Wireless Data...");;

Then, if used in conjunction with the thread example from below, put this in when you want to increase the progress bar


And then finally, when you want it to go away,



Implementing a thread in Android

Here is a simple way to implement a thread into your program.  I usually use it when I want to scan something every few seconds or something.  The onStart and onStop will start and kill your thread.  The sendEmptyMessage is what you use in the thread to update your UI.   All of these methods will go below your onCreate(Bundle whatever) function.

You don’t have to call anything in the onCreate function to make it run.  In this example it will start running when the program starts, however you could call startScan() where ever you want

public void onStart(){

public void onStop(){
    isRunning = false;

public void startScan() {
    new Thread() {
        public void run() {
            while (isRunning) {
                    Thread.sleep(2000); // How long the thread will wait in milliseconds.  Not 100% accurate

                    if(!isRunning) {
                    // Do stuff here
                    hRefresh.sendEmptyMessage(REFRESH SCREEN);
                }catch(Exception e){

// Refresh handler, necessary for updating the UI in a/the thread
Handler hRefresh = new Handler(){
    public void handleMessage(Message msg) {
        case REFRESH_SCREEN:
        //Do stuff in here that you want updated in the screen

Find this helpful? Know a better way of implementing a simple thread? Please feel free to share. Do you need this code uploaded into a sample project? If there is a demand I can start creating basic empty projects that illustrate the code in action. Enjoy!