Reputation: 2191
i need to stop/interrupt a thread made by myself when exiting my app. how can i do this? it should be albe to click on any activity the home button and it should end the thread.
basically the thread i created acts as a session and when one logsout or his session time expires or the app closes then i need to stop the thread. i've managed that for the first 2 cases, but i'm not ble to do it for the third case. infact once i go out of the app in my logCat i can see the thread and when it naturally dies i get a toast notification (which i clearly dont want). tahnks!
Upvotes: 0
Views: 3282
Reputation: 1045
First of all, on hitting home the application is not really exited due to Android's multitasking system. When home is hit the application is paused, so the onPaused method is called. When you hit back, or if the device decides it needs more memory, the application will be killed and onDestroed is called (there are step in between there). See the android lifecycle.Here
If I were you would put the thread stop in the onDestroyed method as that is where the application needs to be created again, but all of them are called when destroyed.
However, in your case it seems that you want something that acts more like a Service. A service is like an activity, but runs in the background, with no UI. Like how pandora plays music without the app being up. With a service you can start it some from any of your activities and end it when any activity is killed (onStop or on Destroy), you could do a semaphore like solution where when all activities using it are killed, it kills itself. And when any activity using it starts(onCreate or onStart), it starts the service. Then you can access the service via static members or keep an instance of it in each activity,
Upvotes: 1
Reputation: 1042
If you want to stop an individual thread yourThread.stop() should work. Otherwise use the answer by Estragon.
Upvotes: 0
Reputation: 4199
It's evil, but did u try
Process.killProcess(Process.myPid());
in the onDestroy of your last activity?
Otherwise, as estragon said, http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle will be the right way to use activities
Upvotes: -3
Reputation: 1462
Im not sure I really understood what you want but you should check the methods relative to an activity lifecycle :
=> http://developer.android.com/reference/android/app/Activity.html
Look for
onPause()
onResume()
onStop()
Then, on each event you do whatever you want with the thread like stopping it
Upvotes: 3
Reputation: 68177
You need to interrupt your thread in onStop method for all your activities. But its not a sophisticated way of doing things. There might be some other solutions, like defining a custom class which extends android's Application class and set your desired logic in that class with static methods, etc.
Upvotes: 0