mardi 3 mars 2015

Android threads can't get notify() to work properly using wait() and notify()



So I am writing an Android application which will do a count down when the user presses a button. A thread runs the count down. My problem is that when I pause the application I want the thread to stop counting and then resume once the application is back. My notify is not working correctly. Help thanks!



public class MainActivity extends Activity {
private TextView mText;
private EditText mUserInput;
private CounterThread mCounterThread;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView)findViewById(R.id.text);
mUserInput = (EditText)findViewById(R.id.userInput);
mCounterThread = new CounterThread();
}

@Override
public synchronized void onPause(){
super.onPause();
mCounterThread.running = false;
}

@Override
public synchronized void onResume(){
super.onResume();
mCounterThread.running = true;
notify();//seems like this does nothing!
}

public void startCounterThread(){
mCounterThread.start();
}

public void button_handler(View v){
startCounterThread();
}

public void updateSeconds(final long seconds){
Runnable UIdoWork = new Runnable(){
public void run(){
String time = String.valueOf(seconds);
mText.setText("Your file will open in " + time + " seconds");
}
};
runOnUiThread(UIdoWork);
}

private class CounterThread extends Thread{
int count = 10;
boolean running = true;

@Override
public synchronized void run(){
while(count != 0){
while(!running){
try{
wait();//wait() will wait forever
//I don't want to put a time since
//I have no clue when the user will resume again
}catch(InterruptedException e){
e.printStackTrace();
}
}

try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
updateSeconds(count--);
}

}
}



Aucun commentaire:

Enregistrer un commentaire