Tuesday 28 August 2012

Start a Service with Alarm Manager Android

At times we need to start or stop a service once a day, once a week or anything like that. We can use AlarmManager in android to start or stop a service at a particular time automatically. This also helps us to start or stop our service at regular intervals.

Here we are dealing with an example to start a service every hour from the time of installation of the application.

Firstly, we will create a class named myService.class. This will be our service. One thing to be noted is that all service classes extends Service. myService.class will be like this.

public class Service_class extends Service {


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

}

here in the onStartCommand method, we return START_STICKY this means that, the service will not be stopped until we manually stop the service.

Now in the main activity, we will have two click listeners for the two buttons ( one for starting the service and the other one for stopping the service ) and the AlarmManager which will start the service at the start of every hour.

public class Main extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Start service using AlarmManager

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 10);
    Intent intent = new Intent(Main.this, Service_class.class);
    PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
            0);
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            36000 * 1000, pintent);

    // click listener for the button to start service
    Button btnStart = (Button) findViewById(R.id.button1);
    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), Service_class.class));

        }
    });

    // click listener for the button to stop service
    Button btnStop = (Button) findViewById(R.id.button2);
    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), Service_class.class));
        }
    });
}

main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp"
    android:text="@string/startservice" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_marginTop="38dp"
    android:text="@string/stopservice" />

</RelativeLayout>

While executing the application, the service will start every hour or when the button start service is pressed. The service will stop only when the stop service button is pressed.

one more thing to be done is that you will have to declare the service in the manifest to make it functional.

<service android:name=".Service_class" />


HAPPY CODING  :)

3 comments:

  1. gr8 post..bt i think there is small typo at

    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
    36000 * 1000, pintent);

    it should be 3600

    ReplyDelete
  2. for android 4.1

    Calendar cal = Calendar.getInstance();
    Intent intent = new Intent(context,
    ServicioChecarActualizacionGuias.class);
    PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0);
    AlarmManager alarm = (AlarmManager) context
    .getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
    30 * 1000, pintent);

    ReplyDelete
  3. will something go wrong when date time change or rebooted. i want to run that service per a week.. messaging services

    ReplyDelete