Alarm Manager Example

前端 未结 10 1777
情话喂你
情话喂你 2020-11-21 05:12

I want to implement a schedule function in my project. So I Googled for an Alarm manager program but I can`t find any examples.

Can anyone help me with a basic alar

10条回答
  •  深忆病人
    2020-11-21 05:57

    I have made my own implementation to do this on the simplest way as possible.

    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    
    import junit.framework.Assert;
    
    /**
     * Created by Daniel on 28/08/2016.
     */
    public abstract class AbstractSystemServiceTask {
    
        private final Context context;
        private final AlarmManager alarmManager;
        private final BroadcastReceiver broadcastReceiver;
        private final PendingIntent pendingIntent;
    
        public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) {
    
            Assert.assertNotNull("ApplicationContext can't be null", context);
            Assert.assertNotNull("ID can't be null", id);
    
            this.context = context;
    
            this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
    
            this.context.registerReceiver(
                    this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener),
                    new IntentFilter(id));
    
            this.configAlarmManager(
                    this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
                    time,
                    alarmType);
        }
    
        public void stop() {
    
            this.alarmManager.cancel(this.pendingIntent);
            this.context.unregisterReceiver(this.broadcastReceiver);
        }
    
        private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) {
    
            Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener);
    
            return new BroadcastReceiver() {
    
                @Override
                public void onReceive(Context context, Intent intent) {
    
                    backgroundTaskListener.perform(context, intent);
                }
            };
        }
    
        private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
    
            long ensurePositiveTime = Math.max(time, 0L);
    
            switch (alarmType) {
                case REPEAT:
                    this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
                    break;
                case ONE_TIME:
                default:
                    this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
            }
        }
    
        public interface BackgroundTaskListener {
    
            void perform(Context context, Intent intent);
    
        }
    
        public enum AlarmType {
    
            REPEAT, ONE_TIME;
    
        }
    
    }
    

    The only next step, implement it.

    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    
    import ...AbstractSystemServiceTask;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * Created by Daniel on 28/08/2016.
     */
    public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask {
    
        private final static String ID = "UPDATE_INFO_SYSTEM_SERVICE";
        private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10);
        private final static AlarmType ALARM_TYPE = AlarmType.REPEAT;
    
        public UpdateInfoSystemServiceTask(Context context) {
    
            super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() {
    
                @Override
                public void perform(Context context, Intent intent) {
    
                    Log.i("MyAppLog", "-----> UpdateInfoSystemServiceTask");
    
                    //DO HERE WHATEVER YOU WANT...
                }
            });
    
            Log.i("MyAppLog", "UpdateInfoSystemServiceTask started.");
        }
    
    }
    

    I like to work with this implementation, but another possible good way, it's don't make the AbstractSystemServiceTask class abstract, and build it through a Builder.

    I hope it help you.

    UPDATED Improved to allow several BackgroundTaskListener on the same BroadCastReceiver.

    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    
    import junit.framework.Assert;
    
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * Created by Daniel on 28/08/2016.
     */
    public abstract class AbstractSystemServiceTask {
    
        private final Context context;
        private final AlarmManager alarmManager;
        private final BroadcastReceiver broadcastReceiver;
        private final PendingIntent pendingIntent;
    
        private final Set backgroundTaskListenerSet;
    
        public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) {
    
            Assert.assertNotNull("ApplicationContext can't be null", context);
            Assert.assertNotNull("ID can't be null", id);
    
            this.backgroundTaskListenerSet = new HashSet<>();
    
            this.context = context;
    
            this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
    
            this.context.registerReceiver(
                    this.broadcastReceiver = this.getBroadcastReceiver(),
                    new IntentFilter(id));
    
            this.configAlarmManager(
                    this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
                    time,
                    alarmType);
        }
    
        public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) {
    
            Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
    
            this.backgroundTaskListenerSet.add(backgroundTaskListener);
        }
    
        public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) {
    
            Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
    
            this.backgroundTaskListenerSet.remove(backgroundTaskListener);
        }
    
        public void stop() {
    
            this.backgroundTaskListenerSet.clear();
    
            this.alarmManager.cancel(this.pendingIntent);
            this.context.unregisterReceiver(this.broadcastReceiver);
        }
    
        private BroadcastReceiver getBroadcastReceiver() {
    
            return new BroadcastReceiver() {
    
                @Override
                public void onReceive(final Context context, final Intent intent) {
    
                    for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) {
    
                        backgroundTaskListener.perform(context, intent);
                    }
                }
            };
        }
    
        private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
    
            long ensurePositiveTime = Math.max(time, 0L);
    
            switch (alarmType) {
                case REPEAT:
                    this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
                    break;
                case ONE_TIME:
                default:
                    this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
            }
        }
    
        public interface BackgroundTaskListener {
    
            void perform(Context context, Intent intent);
    
        }
    
        public enum AlarmType {
    
            REPEAT, ONE_TIME;
    
        }
    
    }
    

提交回复
热议问题