Friday, July 15, 2011

Thread Concepts:

By Magesh Kumar   Posted at  9:59 PM   Android No comments

Method1:
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;


public class Method1 extends Activity {


class PrinterTask extends AsyncTask<String, Void, Void> {


protected Void doInBackground(String... x) {
while (true) {
System.out.println(x[0]);
test();


try {
Thread.sleep(1000);
test2();


} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
};


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


new PrinterTask().execute("---------------------");
//new PrinterTask().execute("foo foo foo");


System.out.println("onCreate() is done.");
}


public void test2() {
// TODO Auto-generated method stub
System.out.println("test2 is done.");
}


public void test() {
// TODO Auto-generated method stub
System.out.println("test is done.");
}
}
Method2:



import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;


public class Method2 extends Activity implements Runnable {


private String pi_string;
private TextView tv;
private ProgressDialog pd;


@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main2);


tv = (TextView) this.findViewById(R.id.tv);
tv.setText("Press any key to start calculation");
}


public boolean onKeyDown(int keyCode, KeyEvent event) {


pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
false);


Thread thread = new Thread(this);

thread.start();



return super.onKeyDown(keyCode, event);
}


public void run() {
pi_string = "gfdsgs";
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}


private Handler handler = new Handler() {
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText(pi_string);


}
};


}


About the Author

Nulla sagittis convallis arcu. Sed sed nunc. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.
View all posts by: BT9

0 comments:

Back to top ↑
Connect with Us

What they says

© 2013 MaGeSH 2 help. WP Mythemeshop Converted by BloggerTheme9
Blogger templates. Proudly Powered by Blogger.