I'm working on a ski tracker app but I've faild at the first task :) the stopwatch
Here is my service:
public class TrackerService extends Service {
private IBinder mBinder = new TrackerBinder();
private TimerThread thread;
private int min =0,sec=0;
private boolean running = true;
@Override
public void onCreate() {
thread = new TimerThread();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void startTimer(){
if(!thread.isAlive())
thread.start();
else{
thread.resume();
}
}
public void pauseTimer(){
thread.suspend();
}
public class TrackerBinder extends Binder{
public TrackerService getService(){
return TrackerService.this;
}
}
public class TimerThread extends Thread{
@Override
public void run() {
while (running){
sec++;
if(sec==60){
min++;
sec=0;
}
try {
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
}
I'm calling the startTimer() and pauseTimer() methodes from the binded activity but at the resume I got java.lang.UnsopportedOperationException. Any idea how to solve it?
Don't ever call stop()
, suspend()
or resume()
on a thread. Those methods have been deprecated for a long time, and the javadocs explain why.
You can do one of two things: 1. keep track of the timer state in your thread class; or 2. start a new thread every time you start the timer, then exit the thread when you stop the timer. The second one is probably what you want.