Thursday, April 19, 2012

Starting service at boot time in android


3 steps to do this

1. Create a Broadcast receiver to receive boot complete state

package com.outsms.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
 
public class StartAtBootServiceReceiver extends BroadcastReceiver 
{
 @Override
 public void onReceive(Context context, Intent intent) 
 {
  if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
   Intent i = new Intent();
   i.setAction("com.outsms.test.StartAtBootService");
   context.startService(i);
  }
 }
}

2. Create a service to be started from BroadCast Receiver


package com.outsms.test;

import android.app.Service;
import android.os.IBinder;
public class OutGoingSMSTestService extends Service {
  
    @Override
    public void onCreate() {
        /*
             Do whatever you want when Srevice first created before started
 */ 
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
     /*
 DO WHATEVER you want when service is started
 */
    }
    @Override
    public void onDestroy() {
     
 /*
        do whatever you want when Service destroyed
    */
       super.onDestroy();
    }
    
 @Override
 public IBinder onBind(Intent arg0) {
  // TODO Auto-generated method stub
  return null;
 }
    
}


3. Modify your AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.outsms.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        
        <service android:name=".OutGoingSMSTestService">
 <intent-filter>
  <action android:name="com.outsms.test.StartAtBootService">
  </action>
 </intent-filter>
</service>

      <receiver android:name=".StartAtBootServiceReceiver">
 <intent-filter>
  <action android:name="android.intent.action.BOOT_COMPLETED">
  </action>
  <category android:name="android.intent.category.HOME">
  </category>
 </intent-filter>
</receiver>      
  
    </application>
</manifest>


start debug it should work fine.

1 comment:

  1. public class OutGoingSMSTestService extends Service

    red underline at "OutGoingSMSTestService"

    What's ploblem?

    ReplyDelete