Tuesday, June 8, 2010

Android background thread, by implementing Thread object, provided with a Runnable object.

In last exercise "Android background thread, by extending Thread", a thread was created by implementing a object of a new class extends Thread. It's another way to create a thread, implement a object of Thread class with a Runnable object provided. Actually, both version have the same out, difference in implementation only.

main.xml is same as last exercise "Android background thread, by extending Thread"

AndroidBackgroundThread.java
package com.exercise.AndroidBackgroundThread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidBackgroundThread extends Activity {

Thread backgroundThread;
TextView myText;
boolean myTextOn = true;
boolean running = false;

Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}

};

void setRunning(boolean b){
running = b;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

myText = (TextView)findViewById(R.id.mytext);

Toast.makeText(this, "onCreate()", Toast.LENGTH_LONG).show();
}



@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();

Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();

backgroundThread = new Thread(new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(handler.obtainMessage());
}
}

});

setRunning(true);
backgroundThread.start();
}

@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();

boolean retry = true;
setRunning(false);

while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();

}
}


Download the files.

No comments:

Post a Comment