Saturday, June 9, 2012

Starting Services on Boot


Most of the projects I work on have lots of backend integrations,some of which update data on a regular basis.  So I set up these integrations within a service that gets started when the device is turned on.  Pretty easy to do. I set up an array in the arrays.xml that has the full path to the service I want to start (packagename+servicename") so for example com.me.myproject.android.services.mygreatservice

The boot service gets the Broadcast message that Android sends out on startup, iterates through array of services and starts them one by one.

You'll need to add the permission below and register the receiver class in the manifest.



  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 <receiver android:name=".services.BootReceiver" >
       <intent-filter >
         <action android:name="android.intent.action.BOOT_COMPLETED" />
       </intent-filter>
     </receiver>      



 public class BootReceiver extends BroadcastReceiver { 
      private static final String TAG ="BootReceiver";
      /**
       * Service intent
       */
      public static Intent mIntent;
      @Override
      public void onReceive(Context context, Intent intent) {
           String[] servs= context.getResources().getStringArray(R.array.services);
            for (int i=0; i<servs.length; i++) {
                 Log.d(TAG, "Starting: "+servs[i]);
                     Intent mIntent = new Intent();                                
                     mIntent.setAction(servs[i]);
                     context.startService(mIntent);
            }
      }
 }  

No comments:

Post a Comment