Android Set multiple repeat alarms

跟風遠走 提交于 2019-12-12 04:51:12

问题


I want to set 3 different alarms repeat everyday.(like 9:00am,1:00pm,6:00pm) And I have created buttons for them. I can set the alarm's time when I click the button. The problem is how can I change my code to achieve above mentioned.

private void setNotification() {
    Intent myIntent = new Intent(getActivity(), MyReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, set_hour);
    calendar.set(Calendar.MINUTE, set_minute);
    calendar.set(Calendar.SECOND,00);
    long startUpTime = calendar.getTimeInMillis();
    System.out.println(startUpTime + "time" + System.currentTimeMillis());
        if (System.currentTimeMillis() > startUpTime) {
            startUpTime = startUpTime + AlarmManager.INTERVAL_DAY;
        }
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startUpTime, AlarmManager.INTERVAL_DAY , pendingIntent);
}

回答1:


As I understand your question you want to set alarm at the click of a button. Use the below two methods to set alarm and cancel alarm. To repeat alarm use a unique requestcode in getBroadcast and when cancelling use the same requestcode value to cancel the alarm which was initially used to start it.

When the button is clicked call setAlarm method.

public void setAlarm(Calendar time,int pk) {
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, pk, alarmIntent, 0);
        manager.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
    }


public void cancelAlarm(int pk) {
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, pk, alarmIntent, 0);
        manager.cancel(pendingIntent);
    }



回答2:


Const.java

public class Const {
   public static final int[] ALARM_HOUR_TIME = {9, 9, 9, 9};
   public static final int[] ALARM_MINUTE_TIME = {29, 30, 31, 32};
}

AlarmManagerUtil.java

public class AlarmManagerUtil {

    AlarmManager alarmManager;
    PendingIntent pendingIntent;

    public void initAlarmNotification(Context context) {

        Calendar calendar = getAlarmDate();

        if (calendar == null) {
            return;
        }

        Intent myIntent = new Intent(context, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);

        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

    public void cancelAlarm(Context context) {
        // If the alarm has been set, cancel it.
        if (alarmManager != null) {
            alarmManager.cancel(pendingIntent);
        }

        // Disable {@code SampleBootReceiver} so that it doesn't automatically restart the
        // alarm when the device is rebooted.
        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    private Calendar getAlarmDate() {
        Calendar calendar = Calendar.getInstance();

        boolean setAlarm = false;
        int hour = Const.ALARM_HOUR_TIME[0];
        int minute = Const.ALARM_MINUTE_TIME[0];

        int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        int currentMinute = calendar.get(Calendar.MINUTE);

        for (int i = 0; i < Const.ALARM_HOUR_TIME.length; i++) {

            if (currentHour <= Const.ALARM_HOUR_TIME[i] && currentMinute < Const.ALARM_MINUTE_TIME[i] && !setAlarm) {
                hour = Const.ALARM_HOUR_TIME[i];
                minute = Const.ALARM_MINUTE_TIME[i];
                setAlarm = true;
            } else if (i == (Const.ALARM_HOUR_TIME.length - 1) && !setAlarm) {
                calendar.add(Calendar.DATE, 1);
                hour = Const.ALARM_HOUR_TIME[0];
                minute = Const.ALARM_MINUTE_TIME[0];
            }
        }

        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);

        Log.d("MyAlarm", "Next Alarm: " + hour + ":" + minute);

        return calendar;
    }
}

AlarmReceiver.java

public class AlarmReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        AlarmManagerUtil alarmUtil = new AlarmManagerUtil();
        alarmUtil.initAlarmNotification(context);

        createNotification(context, 1);
    }

    private static PendingIntent criarPendingIntent(
            Context ctx, int id) {

        Intent resultIntent = new Intent(ctx, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(ctx);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        return stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public static void createNotification(Context ctx, int id) {

        Bitmap largeIcon = BitmapFactory.decodeResource(
                ctx.getResources(), R.mipmap.ic_launcher);

        PendingIntent pitNotificacao = criarPendingIntent(ctx, id);

        Calendar calendar = Calendar.getInstance();

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("My Alarm")
                        .setContentText("HOUR: " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE))
                        .setWhen(System.currentTimeMillis())
                        .setLargeIcon(largeIcon)
                        .setAutoCancel(true)
                        .setContentIntent(pitNotificacao)
                        .setLights(Color.BLUE, 1000, 5000)
                        .setVibrate(new long[]{100, 500, 200, 800})
                        .setNumber(id)
                        .setSubText("GORIO Engenharia");

        NotificationManagerCompat nm = NotificationManagerCompat.from(ctx);
        nm.notify(id, mBuilder.build());
    }
}



回答3:


set your alarm using setRepeat or setInExactRepeat methods



来源:https://stackoverflow.com/questions/28012730/android-set-multiple-repeat-alarms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!