Auto Start Android Service on Boot

For some applications, you will need to have your service up and running when the device is started, without user intervention. Such applications mainly include monitors (telephony, bluetooth, messages, other events).

At least this feature is currently allowed by the exaggeratedly restrictive Android permissions policy.

Step 1: First you’ll need to create a simple service, defined in Monitor.java:

public class Monitor extends Service {
	 
	private static final 	String				LOG_TAG = "::Monitor";
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.e(LOG_TAG, "Service created.");
	}
	 
	@Override
	public void onStart(Intent intent, int startId) {      
		super.onStart(intent, startId);
		Log.e(LOG_TAG, "Service started.");
	}
	@Override
	public void onDestroy() {
	       super.onDestroy();
	       Log.e(LOG_TAG, "Service destroyed.");
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		Log.e(LOG_TAG, "Service bind.");
	    return null;
	}
}

Step 2: Next we need to create a Broadcast receiver class, StartAtBootServiceReceiver.java:

public class StartAtBootServiceReceiver extends BroadcastReceiver 
{
private static final 	String				LOG_TAG = "::StartAtBootServiceReceiver";
    @Override
    public void onReceive(Context context, Intent intent) 
    {
    	Log.e(LOG_TAG, "onReceive:");
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent i = new Intent();
            i.setAction("test.package.Monitor");
            context.startService(i);
        }
    }
}

Step 3: Finally, your AndroidManifest.xml file must contain the following:



	
	
	
    
	
	
	
		
            
                
                
            
        
        
            
                
                
                
                
            
        
    

I need to highlight some of the most important aspects, key factors for possible errors in implementation:
1) The permission android.permission.RECEIVE_BOOT_COMPLETED must be provided (in the manifest xml)
2) The installation must be performed in internal storage, not on SDCARD! To enforce this use android:installLocation=”internalOnly” in the manifest

Leave a Reply