简体   繁体   中英

Alarm manager in a fixed date and time in android

I want to build an android app which will give me an alarm in a fixed date and time. For date I have used date picker and a time picker for taking time in text field. I have merged the date and time in milliseconds by following.

public void mergedt(){
    String myDate = textDate.getText().toString();
    String myTime = textTime.getText().toString();
    String toParse = myDate + " " + myTime;
    // viewtext.setText(toParse + " ");
    try {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm");
        Date date = formatter.parse(toParse);
        millis = date.getTime();
        viewtext.setText(millis + "");
        //viewtext.setText(date + "");
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
}

I have converted current date and time in milliseconds following

long milliseconds = new GregorianCalendar().getTimeInMillis();

For setting the alarm, I have used following code

public void setAlarm(View view){
    long interval = millis - milliseconds;
    long time = new GregorianCalendar().getTimeInMillis() + interval;

    Intent intent = new Intent(this,AlarmReceiver.class);
    AlarmManager alarm_Manager = (AlarmManager)  getSystemService(Context.ALARM_SERVICE);
    alarm_Manager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this, 1,intent, PendingIntent.FLAG_UPDATE_CURRENT));
}

When I set the alarm, it shows the message "alarming" instantly it does not show the alarm in fixed date and time. What is wrong with the code and how can I solve it?

try this: in your mergedt()

try {
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
    Date date = formatter.parse(toParse);
    // millis = date.getTime();
    Calendar calender_alarm.setTime(date);
    millis=calender_alarm.getTimeInMillis();
    viewtext.setText(millis + "");
    //viewtext.setText(date + "");
} catch (ParseException pe) {
    pe.printStackTrace();

}

Get your current time like:

    Calendar calNow = Calendar.getInstance();
   long current_time = calNow.getTimeInMillis();

Now check alarm time:

     if (millis > current_time) {
        //call setAlarm() method
 }

In your setAlarm() method change:

alarm_Manager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this, 1,intent, PendingIntent.FLAG_UPDATE_CURRENT));

to:

alarm_Manager.set(AlarmManager.RTC_WAKEUP,millis, PendingIntent.getBroadcast(this, 1,intent, PendingIntent.FLAG_UPDATE_CURRENT));

change the time value..to millis

You are trying to get date and time value from the picker, so you can use this class. Get time and date and set alarm.

public class MainActivity extends AppCompatActivity {


public static int alarmHour, alarmMin, alarmDay, alarmYear, alarmMonth;
final static int RQS_1 = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void setDate(View view) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

public void setTime(View view) {

    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}


public void setAlarm(View view) {
    Calendar calNow = Calendar.getInstance();
    Calendar calSet = (Calendar) calNow.clone();
    calSet.set(Calendar.HOUR_OF_DAY, alarmHour);
    calSet.set(Calendar.MINUTE, alarmMin);
    calSet.set(Calendar.DAY_OF_MONTH, alarmDay);
    calSet.set(Calendar.YEAR, alarmYear);
    calSet.set(Calendar.MONTH, alarmMonth);

    setAlarmN(calSet);
}

private void setAlarmN(Calendar targetCal) {

    Toast.makeText(this, "Alarm is set at" + targetCal.getTime(),
            Toast.LENGTH_LONG).show();
    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            getBaseContext(), RQS_1, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
            pendingIntent);

}

//date picker fragment
public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        alarmDay = day;
        alarmYear = year;
        alarmMonth = month;
    }
}

//Time picker fragment 
public static class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
        alarmHour = hourOfDay;
        alarmMin = minute;
    }
}


}

full project link: https://github.com/milon87/AlarmSpecificTime

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