I have an Activity (called StartActivity) that starts a Service. The Service calls methods in my MainActivity class. The process is supposed to repeat on a timer which is inside the Service class. The program stops after one execution however, it is apparently not rescheduled. I know the onStart command is given to the Service when the Activity is started because the program functions the first time, when the activity is clicked. Neither task runs again. Any advice would be welcome. TLDR: Timer is not calling method repeatedly. It only works the first time.
Service Class
import java.util.TimerTask;
import java.util.Calendar;
import java.util.Timer;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class SvcActivity extends Service {
TimerTask questionTask;
TimerTask gpsTask;
Handler handler = new Handler();
Timer t = new Timer();
@Override
public int onStartCommand(Intent i,int flags,int startID) {
Log.i("AAA","---In service---");
questionTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
if(getHour()>=10&&getHour()<=22)
{
Intent i=new Intent(SvcActivity.this,MainActivity.class);
i.putExtra("key", "setup");
i.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i("AAA","---right before startActivity---");
startActivity(i);
}
else
Log.i("AAA","---not between 10am and 10pm. Correct!");
}
});
}
};
gpsTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Log.i("AAA","---in async task");
if(MainActivity.con!=null)
{
Log.i("AAA","---about to call async task");
BackgroundActivity objAsyncTask = new BackgroundActivity();
objAsyncTask.execute();
}
}
});
}
};
int q=(int)(Math.random() * 2);
if(q<1)
{
// first run, subsequent time delay. in miliseconds
t.schedule(questionTask, 300, (3600000+2700000)); // 1 hour 45 min
}
else
t.schedule(questionTask, 300, (7200000+900000)); // 2 hour 15 min
t.schedule(gpsTask, 300, 300000);// 5 min
return START_STICKY;
}
//-----------------------------get hour------------------------------------------
public int getHour()
{
Calendar c=Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
return hour;
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}