Android/Java - pause thread
I'm new to this, so maybe it's trivial to everybody, but I just can't figure out, why this isn't working. I've read about it, tried many way, and still not working. So I want to pause a thread in android (java). I want this to run, freeze the screen for 1 sec, and continue working. That's all. Why isn't this working?
public class Game extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate开发者_运维技巧(savedInstanceState);
setContentView(R.layout.game);
runner.join();
runner.start();
// do stuff
pause();
// do stuff
}
private boolean running = true;
private boolean paused = false;
public void setRunning(boolean run) {
running = run;
}
public void pause() {
paused = true;
}
Thread runner = new Thread() {
public void run() {
while (running) {
try {
//do stuff
Thread.sleep(100);
while (paused) {
try {
Thread.sleep(1000);
} catch (Exception e) {
} finally {
paused = false;
}
}
} catch (Exception e) {
}
}
}
};
}
You should change the order of the methods call, you coded:
runner.join();
runner.start();
Change to:
runner.start();
runner.join();
And it should work.
Call Thread.sleep
in the onCreate
method. Throw out all the thread stuff. It is just wrong.
Why at all you want to freeze the screen? This is a very bad approach. Use Dialog instead.
if you need freeze screen, you only need use SystemClock.sleep(millis).//1000 = 1 second Android use a main thread for your interface very different . Your code try stop it like a java program.
Example
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SystemClock.sleep(1000);
...
or search info like this:
//this is similar to your thread
new Thread(new Runnable() {
@Override
public void run() {
//some code
int val = 1+ 1; //code here dont interrupt main thread
//this code run on main thread
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
//freeze Views
SystemClock.sleep(1000);// 1 second
}
});
}
});
use this
delayprg(3000);//3seg
private void delayprg(int delayc) {
try {
Thread.sleep(delayc);
} catch (InterruptedException e) {
}
}
You must avoid spinning try this:
private boolean isPaused = false;
public synchronized void pause(){
isPaused = true;
}
public synchronized void play(){
isPaused = false;
notifyAll();
}
public synchronized void look(){
while(isPaused)
wait();
}
public void run(){
while(true){
look();
//your code
}
精彩评论