I have a service class in my Android app which uses a timer. The timer is set to run at a delay of 1min (60000ms). I want the user to be able to dynamically change this delay. Normally, in java I could just use timer.setDelay(); but Android does not have this function.
Service class so far:
public class LocalService extends Service
{
Timer timer = new Timer();
int newDelay;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
mainTask();
}
}, 0, 60000);
}
private void mainTask()
{
//do something
}
private void shutdownService()
{
if (timer != null) timer.cancel();
}
public void onDestroy()
{
super.onDestroy();
shutdownService();
}
private void readNewDelay()
{
InputStream in = openFileInput("updateDelay");
if(in != null)
{
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
newDelay = Integer.parseInt(buffreader.readLine()) * 60000; //value in file is saved in minutes
}
in.close();
}
}
The delay I want is saved to a text file by an activity. I then want the service to read this file and update its timer delay accordingly.