指定天数

时间:2017-04-18 05:03:08

标签: android android-studio

以下是我的代码,以便在我的应用程序中启动alarm

public static void startReferAlarm(Context context,String[] message,String activityToOpen) 
{
    try {

        Log.d("Refer friend Activity", "Alarm On");
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 8);
        Intent myIntent = new Intent(context, AlarmReciever.class);
        myIntent.putExtra("message",message);
        myIntent.putExtra("äctivityName",activityToOpen);

        final int _id = (int) System.currentTimeMillis();
        PendingIntent appIntent = PendingIntent.getBroadcast(context, _id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        //48*60*60*1000

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                48*60*60*1000, appIntent);

    }catch (Exception e) {
        Log.d("MyActivity", "Alarm Off");
        e.printStackTrace();
    }
}

从我上面的代码中,代码将启动警报并在上午8点时通知,然后在 48小时后重复

但是我希望在48 hours之后启动闹钟,或者在7 hours之后发言,然后在每48 hours之后重复。

请帮我解释逻辑。谢谢。

2 个答案:

答案 0 :(得分:1)

不要使用calender.set(Calendar.HOUR, 8),因为它会将小时数设置为8'o clock

尝试

//if you want to add 7 hours
calender.add(Calender.HOUR, 7); //this will add 7 hours to current time

//if you want to add 7 days
calender.add(Calender.DAY_OF_MONTH, 7); //this will add 7 days to current time

// interval to repeat alarm after 48hours
int interval = 48 * 60 * 60 * 1000; 

如果要以24小时格式使用,请将Calendar.HOUR替换为Calendar.HOUR_OF_THE_DAY

请参阅重复警报问题How to repeat alarm in android 6.0

的答案

答案 1 :(得分:1)

任何仍然困惑的人。以下方法将在其将在上午9点通知的任何特定操作后7天启动警报,并在48小时后重复。

 public static void startCreateProfileAlarm(Context context,AlarmManager alarmManager ,String[] message,String activityToOpen) {

    try {

        //working code
        Calendar calendar = Calendar.getInstance();
        calendar.add(DAY_OF_MONTH,7);
        //calendar.add(Calendar.HOUR_OF_DAY,1);
        calendar.set(Calendar.HOUR_OF_DAY, 9);

        // we can set any time here
        //calendar.set(Calendar.HOUR_OF_DAY, 10);

        Intent myIntent = new Intent(context, AlarmReciever.class);
        myIntent.putExtra("message",message);
        myIntent.putExtra("äctivityName",activityToOpen);


        final int _id = (int) System.currentTimeMillis();

         createProfileAppIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        //48*60*60*1000
        //2*60*1000
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                48*60*60*1000, createProfileAppIntent);


    }catch (Exception e) {
        Log.d("MyActivity", "Alarm Off");
        e.printStackTrace();
    }
}