I’m asking for help so my life, and more importantly my user’s lives will not be ruined by me not knowing how to use Services and Threads correctly.
I’m not asking for a long explanation, but more of a confirmation. It’s fine if I’m dead wrong. I’m here to learn.
If I understand correctly:
1. a service runs in the background (no UI).
2. a service theoretically will run forever until it kills itself (I’m taking a big guess here)
3. a service will continue to run even when the main Activity is not visible (how about even destroyed?)
So here’s my coding question.
I’ve got my service setup and a thread. Everything works great, but it only works once. I need it to loop and keep checking back. Once it’s done run() how do I go about telling it to run() again?
public class NotifyService extends Service{
private long mDoTask;
NoteThread notethread;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
mDoTask = System.currentTimeMillis();
notethread = new NoteThread();
notethread.start();
}
public class NoteThread extends Thread {
NotificationManager nManager;
Notification myNote;
@Override
public synchronized void start() {
super.start();
//init some stuff
}
@Override
public void run() {
//If it's been x time since the last task, do it again
//For testing set to every 15 seconds...
if(mDoTask + 15000 < System.currentTimeMillis()){
//Take care of business
mDoTask = System.currentTimeMillis();
}
}
}
}
From the Android docs:
In other words, a service does NOT run in the background unless you put it in a thread. If you put a service that never ends in your application without manually threading the service, then it WILL block.
Android provides an API to do background tasks for you without having to poke around with Java threads; it’s called AsyncTask and it’s one of the few GOOD design decisions that the Android team has ever made.
EDIT I forgot to address your question about multithreading. You don’t want to make a thread execute its
run()method more than once. Either instantiate a new thread or put awhileloop around the contents of therunlogic that you would like to have repeated.