set Alarm by Activity, service or receiver - Android Android OS

Android examples for Android OS:Alarm Set Up

Description

set Alarm by Activity, service or receiver

Demo Code


//package com.java2s;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class Main {

    public static void set(Context ctx, String className, int alarmId,
            int type, long triggerAtTime, boolean setAlarm) {
        try {//from  w w w .  j  a  v  a  2  s .  c  o  m
            Intent intent = new Intent(ctx, Class.forName(className));
            intent.putExtra("alarmId", alarmId);
            PendingIntent pendingIntent = null;
            switch (type) {
            case 1:// activity
                pendingIntent = PendingIntent
                        .getActivity(ctx, 0, intent, 0);
                break;
            case 2:// service
                pendingIntent = PendingIntent.getService(ctx, 0, intent, 0);
                break;
            case 3:// receiver
                pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent,
                        0);
                break;
            default:
                break;
            }

            AlarmManager alarmManager = ((AlarmManager) ctx
                    .getSystemService(Context.ALARM_SERVICE));
            if (setAlarm) {
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        System.currentTimeMillis() + triggerAtTime,
                        pendingIntent);
            } else {
                alarmManager.cancel(pendingIntent);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials