I have the following timer in my application:
public class MainScreen extends ApplicationActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}
public static class ScheduleSomething extends TimerTask {
@Override
public void run() {
System.out.println("This is a test!");
}
}
}
Each second the message "This is a test!" is displayed, but when I close the application it stops the timer also. Is there any way to keep this timer running when I close the application?
I tried to:
public void onStop(Bundle savedInstanceState) {
super.onStop(savedInstanceState);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}
public void onDestroy(Bundle savedInstanceState) {
super.onDestroy(savedInstanceState);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}
But it doesn't work...
Use a broadcast receiver to keep running the timer after killing application every minute:
And in the class below, do whatever you want in onHandleIntent method that is called every minute from TimerReceiverSyncInterval class:
Make a entry in the manifest file:
And finally register the broadcast receiver from MainActivity like this: