Showing posts with label Multiple-Thread-Android. Show all posts
Showing posts with label Multiple-Thread-Android. Show all posts

Wednesday 27 April 2011

How to Start Multiple Thread in Android

here is the code of java where define two thread for android application main class


package com.practice.secondhand;

import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class SecondHand extends Activity {
// private Handler mHandler = new Handler();
protected static final String TAG = SecondHand.class.getName();
private ImageView img;
Handler mHandler;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread = new Thread(runnable);
myThread.start();

}

private void doPlay(){
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

Log.v("log_tag", "this is seocond thread");

}
}).start();
}
public void doRotate() {

runOnUiThread(new Runnable() {
public void run() {
try {

Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + "::" + seconds;
Log.v("log_tag", "Log is here Time is now" + curTime);
img = (ImageView) findViewById(R.id.imgsecond);
RotateAnimation rotateAnimation = new RotateAnimation((seconds - 1) * 6, seconds * 6,
Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);

rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setFillAfter(true);

img.startAnimation(rotateAnimation);
} catch (Exception e) {
Log.e("log_tag", "Error msg is " + e.toString());

}
}
});
}

class CountDownRunner implements Runnable {
// @Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// Log.v("log_tag", "Roate is going");
doRotate();
Thread.sleep(1000);
doPlay();
} catch (InterruptedException e)
{
// Thread.currentThread().interrupt();
} catch (Exception e) {
Log.e("log_tag", "Error is " + e.toString());
}
}
}
}

}


in this class doRotate(); function is for the updating ui thread in my class it is for the analog clock second hand for updating second hand .and doPlay() is thread for doing any other thing at every one second.