如何在设定时间之前启动闹钟?

时间:2018-10-12 06:36:33

标签: android alarmmanager alarm android-alarms

class ClassAlarmReceiver extends WakefulBroadcastReceiver {

AlarmManager mAlarmManager;
PendingIntent mPendingIntent;

public static final long INTERVAL = 1000 * 60 * 60 * 24;
static final long ONE_MINUTE_IN_MILLIS=60000;

@Override
public void onReceive(Context context, Intent intent) {
    int mReceivedID = Integer.parseInt(intent.getStringExtra(ClassEditActivity.EXTRA_REMINDER_ID));

    // Get notification title from Reminder Database
    ReminderDatabase rb = new ReminderDatabase(context);
    Classes classes = rb.getClasses(mReceivedID);
    String mTitle = classes.getTitle();

    // Create intent to open ReminderEditActivity on notification click
    Intent editIntent = new Intent(context, ClassEditActivity.class);
    editIntent.putExtra(ClassEditActivity.EXTRA_REMINDER_ID, Integer.toString(mReceivedID));
    PendingIntent mClick = PendingIntent.getActivity(context, mReceivedID, editIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    //Set Alarm Ringtone
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager.getRingtone(context, notification);


    // Create Notification
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.app_logo))
            .setSmallIcon(R.drawable.schoolbuddy_white)
            .setContentTitle(context.getResources().getString(R.string.app_name))
            .setTicker(mTitle)
            .setContentText(mTitle)
            .setSound(Uri.parse("android.resource://"
                    + context.getPackageName() + "/" + R.raw.buzz_alarm))
            .setContentIntent(mClick)
            .setAutoCancel(true)
            .setOnlyAlertOnce(false)
            .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
            .setLights(Color.MAGENTA, 3000,3000);



    NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(mReceivedID, mBuilder.build());

    r.play();

}

上面是我的OnReceive代码。我认为问题不存在。但是在这里:

public void setAlarm(Context context, Calendar calendar, int ID) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, ClassAlarmReceiver.class);
    intent.putExtra(ClassEditActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long afterAdding15Mins = currentTime + ( 15 * ONE_MINUTE_IN_MILLIS);
    long diffTime = calendar.getTimeInMillis() - currentTime;


    // Start alarm using notification time
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + diffTime ,
            mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, ClassBootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

我正在创建一个应用程序,该应用程序会在设置的时间之前启动警报。例如,如果我将其设置为上午9:30,那么如果用户将其设置为15分钟,它将能够在9:15发出警报。请帮助我在任何地方都找不到解决方案。

2 个答案:

答案 0 :(得分:0)

ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();

SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    Date date = originalFormat.parse(model.getDate());

    Calendar calendarBegin = Calendar.getInstance();
    calendarBegin.setTime(date);

    values.put(CalendarContract.Events.DTSTART, calendarBegin.getTimeInMillis());
    values.put(CalendarContract.Events.TITLE, model.getTitle());
    values.put(CalendarContract.Events.DESCRIPTION, model.getDetail());
    values.put(CalendarContract.Events.ALL_DAY, 0);

    Calendar calendarEnd = Calendar.getInstance();
    Date endDate = originalFormat.parse(model.getEndDate());
    calendarEnd.setTime(endDate);

    values.put(CalendarContract.Events.DTEND, calendarEnd.getTimeInMillis());

    TimeZone timeZone = TimeZone.getDefault();
    values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        values.put(CalendarContract.Events.CALENDAR_ID, 3);
    } else {
        values.put(CalendarContract.Events.CALENDAR_ID, 1);
    }

    values.put(CalendarContract.Events.HAS_ALARM, 1);

     Uri event = cr.insert(CalendarContract.Events.CONTENT_URI, values);
            ToastUtil.showToast(getActivity(), R.string.alert_add_event);

            // this is for 1hour before
            Uri REMINDERS_URI_ONE = Uri.parse(CalendarUtil.getCalendarUriBase(true) + "reminders");
            values = new ContentValues();
            values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
            values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
            values.put(CalendarContract.Reminders.MINUTES, 60);
            cr.insert(REMINDERS_URI_ONE, values);

             // this is for 1day before
            Uri REMINDERS_URI_TWO = Uri.parse(CalendarUtil.getCalendarUriBase(true) + "reminders");
            values = new ContentValues();
            values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
            values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
            values.put(CalendarContract.Reminders.MINUTES, 60 * 24);
            cr.insert(REMINDERS_URI_TWO, values);

答案 1 :(得分:0)

我找到了解决我问题的方法。谢谢所有帮助我的人。

// Set up calender for creating the notification
    mCalendar.set(Calendar.MONTH, --mMonth);
    mCalendar.set(Calendar.YEAR, mYear);
    mCalendar.set(Calendar.DAY_OF_MONTH, mDay);
    mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
    mCalendar.set(Calendar.MINUTE, (mMinute - 15));
    mCalendar.set(Calendar.SECOND, 0);

在设置通知时,我已经调整了分钟,以便闹钟在调整后的时间开始。

mCalendar.set(Calendar.MINUTE, (mMinute - 15));

在这里,我从分钟设置中减去了15分钟。