I have created a sample/demo/test program in Android that runs quite nicely, if you see below you will see I have created a thread. Now I want to create another thread to work with another handler… since I cannot have two run() methods… how do I do this?
This is my (working – no errors) program:
package com.ryan1;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class main extends Activity implements Runnable{
int level = 0;
int seconds_running=0;
TextView the_seconds,the_level;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
the_seconds = (TextView) findViewById(R.id.textview_seconds);
the_level = (TextView) findViewById(R.id.textview_level);
Thread thread = new Thread(this);
Thread thread2 = new Thread(this);
thread.start();
thread2.start();
}
public void run() {
while(seconds_running<500)
{
if(seconds_running %5 ==0){level++;}
try {
handler.sendEmptyMessage(0);
int a = 1000 - (level*100);
if(a<=100){a=25;}
Thread.sleep(a);
System.out.println("R "+Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
seconds_running++;
int a = 1000 - (level*100);
the_seconds.setText(" "+seconds_running);
the_level.setText(level+" "+a);
}
};
}
Use anonymous class like this.