Generally speaking, there are several mechanisms for doing what you are attempting to doing, with varying levels of complexity and effectiveness. I'd like to broadly describe a few.
Services
Services can be thought of as headless Activities. The idea is that a Service publishes an interface through which other code can interact with it. A service is managed by Android, started when needed, shutdown when not.
A service provides some unique qualities: (From linked doc)
- A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
- A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.
So, you'll want to use a service when you want some processing done in a fashion that allows it to be continued after the activity is stopped or you'd like to share a single instance of the processing code between multiple apps.
In my opinion, this comes with some complexity. Simple Services are, by design simple. Complex services are very complex, requiring lots of design effort. On top of this, Services are something that tend to be 'nuked' by poorly informed users with TaskKillers.
HandlerThread
The second option is a HandlerThread. I find this to be a bit less complex in terms of both application construction and maintenance. Handlers use a system of messages and queues to communicate. This creates a nice balance, in my opinion, between code complexity and the ability to decouple a private worker service from other components of the app. You would need to manage the life cycle of this HandlerThread by calling start() on the HandlerThread from an owning class and then sending it a message you define to be the shutdown message and having it stop itself. You can find an example of the configuration here
Runnable
The classic example of how to do bare bones multi threading. You've already got and idea for how to do this. The best example of a way to stop a single thread is setting your own environment variable to be monitored by the thread.
private static boolean stop = false;
new Thread(new Runnable {
public void run(){
if(!stop){
//do work
}
}
});
Thread.sleep(1000);
stop = true;
You can find a good discussion on this topic here
Based on the stage it looks like you are at, you can certainly consider switching to one of the other more robust threading options based on your requirements.