Pages

Tuesday, March 27, 2012

[Android] Launch a service daily using AlarmManager

If you have heard crond in Linux kernel, AlarmManager is the counterpart in Android.



hint:  Activity can be regard as a foreground process.
         Service can be regard as a background process.

Task: Check something at everyday midnight automatically (User do not need to operate)

So, we need:
1. A Service that perform the task (in background). - CronService.java
2. An Activity that launch Service periodically. - CronTestActivity.java
3. Register the Service in Manifest.xml

Step 1. Create the Service you want:

public class CronService extends Service{
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
       Toast.makeText(this, "Service start... ", Toast.LENGTH_SHORT).show();
    }
}

Step 2. Create the main activity and set up and schedule

public class CronTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Calendar cal= Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE,30);
        cal.set(Calendar.SECOND, 00);
     
       //Start the Service since today night, 11:30 p.m      

        Intent intent=  new Intent(this, CronService.class);
        PendingIntent pIntent = PendingIntent.getService(this,0, intent, 0);
       
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24*60*60*1000, pIntent);

      //launch it every 24 hours
    }
}

step 3. Don't forget to register the Service in Manifest

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".CronTestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <service android:name=".CronService"></service>
    </application>



By doing so, your process will be launched automatically every night since the user launch the app.
reference:
http://stackoverflow.com/questions/9004635/android-how-should-i-run-a-service-daily-and-12pm-using-alarmmanager

No comments:

Post a Comment