简体   繁体   中英

Run PendingIntent in exact time

Everybody.

I've got this code snippet.

pending_intent = PendingIntent.getActivity(context, 0, intent, 0);
alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC, System.currentTimeMillis() + runDelay, pending_intent);

I want to get rid of System.currentTimeMillis() + runDelay, and pass just runDelay variable intofunction, does someone know what I should do?

PS I need code to be API8

Thanks a lot.

Use a TimePickerDialog to get the runDelay from user to do so

class variable:

private TimePickerDialog time_picker;
private Calendar targetCal;

A class constructor

public YOurClassName() {

        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

    }

inside onCreate() or onActivityCreated():

time_picker = new TimePickerDialog(getActivity(), mTimeSetListener,
            mHour, mMinute, false);

Inside the class:

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        // the callback received when the user "sets" the TimePickerDialog in
        // the dialog
        public void onTimeSet(TimePicker view, int hourOfDay, int min) {

            hour = hourOfDay;
            minute = min;

            Calendar calNow = Calendar.getInstance();
            Calendar calSet = (Calendar) calNow.clone();

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

            if (calSet.compareTo(calNow) <= 0) {
            // Today Set time passed, count to tomorrow
            calSet.add(Calendar.DATE, 1);
            }
            targetCal = calSet;
            }
    };

use the targetCal in your code like this

alarm.set(AlarmManager.RTC, targetCal.getTimeInMillis(), pending_intent);

I hope this would help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM