Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting background service when Android turns on

I need to have ALWAYS a background service that will synchronize my Android application and a server. I know how to launch it through my application, but when the Android turns off, then the background service will die.

How can I do to keep the background service always running? (Even when the device turns off and then turns on...)

I need to add to the starts programs of Android my background service. Any hints?

like image 365
Frion3L Avatar asked Jun 23 '12 10:06

Frion3L


People also ask

What is background services in Android?

A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

How do I turn off background services on Android?

Stop Services Running in BackgroundOpen Settings of the phone. Now, go to the Developer Options. Tap on Running Services. Tap on the app for which you want to limit battery usage, now tap on stop.


2 Answers

use <action android:name="android.intent.action.BOOT_COMPLETED" /> for starting your service when the device turns on.

In AndroidManifest.xml:

 <receiver android:name=".BootBroadcastReceiver" >   
            <intent-filter>   
                <action android:name="android.intent.action.BOOT_COMPLETED" />   
            </intent-filter>   
        </receiver> 

Add permission in your AndroidManifest.xml as:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>

In code part BootBroadcastReceiver:

public class BootBroadcastReceiver extends BroadcastReceiver {     
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";   
    @Override   
    public void onReceive(Context context, Intent intent) {   
        // BOOT_COMPLETED” start Service    
        if (intent.getAction().equals(ACTION)) {   
            //Service    
            Intent serviceIntent = new Intent(context, StartOnBootService.class);       
            context.startService(serviceIntent);   
        }   
    }    
}   

EDIT: if you are talking about device screen on/off then you need to register <action android:name="android.intent.action.USER_PRESENT" /> and <action android:name="android.intent.action.SCREEN_ON" /> for starting your service when user is present or screen is on.

like image 88
ρяσѕρєя K Avatar answered Nov 05 '22 03:11

ρяσѕρєя K


(Even when the device turns off and then turns on..

The OS broadcasts ACTION_BOOT_COMPLETED when it has finished booting. Your app can ask to receive this notification by requesting permission in your manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>

http://blog.gregfiumara.com/archives/82

http://www.androidcompetencycenter.com/2009/06/start-service-at-boot/

like image 23
Dheeresh Singh Avatar answered Nov 05 '22 01:11

Dheeresh Singh