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.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setMessage("Gathering Wireless Data...");
mDialog.show();
mDialog.setProgress(0);
mDialog.setMax(60);

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


mDialog.incrementProgressBy(1);

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


mDialog.dismiss();

ez

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

@Override
public void onStart(){
    startScan();
    super.onStart();
}

@Override
public void onStop(){
    isRunning = false;
    super.onStop();
}

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

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

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

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!