I am new to Android services so I had some questions that would clarify how I could use them in my current project.
1) Do I need to have my application running to have the service running? Do I have to launch the application for the services to start?
2) I want to print a text on the screen at the end of my service run. First, is it possible and second, will I be able to see this text on the Activity UI when I switch to the Activity’s screen?
3) I want my service to use variables and functions that are implemented in the main Activity class. Is it possible?
4) Related to question 3: I have an AsyncTask in my current application that repeats every minute using a TimerTask. I want to have the same functionality, but this time running in the background when user is busy doing something else. Is Service the right thing to do that? Can I accomplish that by running my searchRegularly() (which is in the Activity) function from the Service? Below, backgroundSearch is the name of the AsyncTask that runs every minute.
public void searchRegularly() {
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
searchTimer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
backgroundSearch = new SearchTask();
backgroundSearch.execute();
}
});
}
};
searchTimer.schedule(doAsynchronousTask, 1000,60000);
}
5) How do you decide to use whether a Service or an IntentService? What is the main difference?
1) No. But the application (I mean the Application class in Manifest, not activity) will be created before your service
2) Do you mean “toast“? Yes
3) Though it’s possible with some tricks, this is not recommended. Rethink your design.
4) Service can do, or you can consider AlaramManager
5) Service itself should be a Singleton, no two service of the same class will be running at the same time; for Service, if you call multiple StartService, and if Service is already running, it will not Start twice. But IntentService will work on multiple “start” simultaneously.