Well what I am trying to do, is to make a function run every,let's say, 10 seconds. Now also I'm trying to make this function stops when the user press on an exit button which finish the activity. But if let's say the user press on home or back , when he's at the activity, then I want the function to run in the background.
In order to do so I've done the next few steps -
I've declared on the activity at the manifest as follows -
<activity android:name="com.example.one.ViewList" >
<intent-filter>
<action android:name="android.intent.action.MAIN" >
</action>
<category android:name="android.intent.category.NORMAL" >
</category>
</intent-filter>
</activity>
At the code of this ViewList activity, I've use the next code at the onResume function -
myTimer = new Timer();
MyTimerTask myTimerTask= new MyTimerTask();
myTimer.scheduleAtFixedRate(myTimerTask, 0, 10000);
I've also added the next class at the activity code -
private class MyTimerTask extends TimerTask {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//code to get and send location information
Log.d("MY TIMER TASK", "RUNNING");
}
});
}
}
Now at the onClick of the exit button, I've sdded the next code -
myTimer.cancel();
finish():
The interesting thing is - when the activity is running and I pressed on the exit button, then the function is sure stopping.
When I'm at the activity and press back or home buttons - the function is running as I wanted it to run, at the background.
But when I come back to the activity and press on the exit button the function keeps on running at the background, even though that the app was closed.
So how can I stop this function when I press on a button and not when destroying the activity?
Thanks for any kind of help