Search code examples
androidservicebroadcastreceiveralarmmanagerintentservice

Service, IntentService, BroadcastReceiver or AlarmManager?


I wish everyone is ok.

I've been reading a lot and I'm kind of lost, I'm completly new to Android and I want to make an App.

My first approach was to make an activity but I need my App to keep runing, so I came to think and use Service. Actually the problem is that I need the service to never stop, also when the phone restart or reboot to start the service again.

I've figure it out how to start the service after the reboot/restart.

What I'm doing is to start my service from my only activity this way:

------------------- The Activity -------------------------

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(MyActivity.this, MyService.class));

}

------------------- The Service -------------------------

@Override
public void onCreate() {
    Toast.makeText(this, "Auto Service Created onCreate", Toast.LENGTH_LONG).show();   
}

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    Timer timer;

    Toast.makeText(this, "Auto Service onStartCommand", Toast.LENGTH_LONG).show();

    int delay = 5000; // delay for 5 sec.
    int period = 5000; // repeat every sec.

    timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask(){
        public void run() 
        {
            System.out.println("Auto Service: Runing!");
        }   
    }, delay, period);


    return START_STICKY;
}

It does work perfectly if the activity is runing or in background, but when it is send to the task list and I do manually eliminate it from there the service stops and I don't want that to happend.

QUESTIONS.-

1.- ¿How to make my service to don't get kill and keep runing?

2.- ¿Would it be better to have a BroadcastReceiver to get an especific intend then execute my activity? (to improve battery to improve battery consumption)

3.- If Question 2 is a better aproach, ¿Do I still need a service or could I rely on activities?

Thank you in advance!!!

EDIT 1.-

Actually what I want to achieve is to launch an activity when the screen goes on (don't know yet if it's better to start it when the screen goes off or when screen goes on) do some work then finish the activity.

Then again repeat the activity every time the screen goes on and even to keep running or start running the activity when the phone restart or reboot, much like a lockscreen app.


Solution

  • To answer your question No. 1

    How to make my service to don't get kill and keep runing?

    Your processes including services can be killed at any time, for any reason, based on user activity (like recent tasks list, a third-party task manager, "Force Stop" in Settings, etc.) or based on OS needs (system RAM is getting low). You cannot prevent this.

    You can take some steps to minimize the odds of the OS deciding on its own to terminate your process, such as using startForeground() on the service, but this does block the user from doing what the user wants with your app's process.

    So as system can terminate the service, there are 2 ways to overcome this :

    1. If you are implementing the service, override onStartCommand() and return START_STICKY(which you are doing right now) as the result. It will tell the system that even if it will want to kill your service due to low memory, it should re-create it as soon as memory will be back to normal.
    2. If you are not sure 1st approach will work - you'll have to use AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html . That is a system service, which will execute actions when you'll tell, for example periodically. That will ensure that if your service will be terminated, or even the whole process will die(for example with force close) - it will be 100% restarted by AlarmManager at the scheduled time.

    Question No. 2

    Would it be better to have a BroadcastReceiver to get an especific intend then execute my activity?

    That depends on what you want to achieve with your BroadcastReceiver.For example if you want to do something when connectivity state of device changes or device is rebooted, you should use BroadcastReceiver instead of services.

    Also keep it in mind that, your services should not keep on running for a long period of time or so frequently(like in every 15-30 min) that it causes heavy battery drainage.

    Question No. 3

    If Question 2 is a better aproach, ¿Do I still need a service or could I rely on activities?

    As i said it depends on what you are trying to achieve.There is no such rule that you need to use a Service if you use a BroadcastReceiver or vice versa.

    If all you want is to perform some particular background task in a periodical manner(for example once everyday or once in 2 days) then you should use AlarmManager with PendingIntent to schedule your Service.At the scheduled time, the service will be started automatically,it will do what it's suppose to do,and as soon as it completes the task,the service needs to be stopped.Again at the next scheduled time the service will start again,do it's job and then stop.This process continues.