Android 如何使用报警管理器区分am和pm报警?

Android 如何使用报警管理器区分am和pm报警?,android,Android,我正在为约会提醒创建报警警报,因为我正在使用以下代码。代码运行得很好,它向我显示报警警报,但唯一的问题是,它不能区分am和pm之间的报警,假设我在设备中设置了7am和当前7pm,那么我的报警对话框也会显示。我如何管理上午和下午?我使用这个链接作为参考 AlertDemo.class import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; impo

我正在为约会提醒创建报警警报,因为我正在使用以下代码。代码运行得很好,它向我显示报警警报,但唯一的问题是,它不能区分am和pm之间的报警,假设我在设备中设置了7am和当前7pm,那么我的报警对话框也会显示。我如何管理上午和下午?我使用这个链接作为参考

AlertDemo.class

 import android.app.AlertDialog;
 import android.app.Dialog;
 import android.content.DialogInterface;
 import android.content.DialogInterface.OnClickListener;
 import android.os.Bundle;
 import android.support.v4.app.DialogFragment;
 import android.view.WindowManager.LayoutParams;


public class AlertDemo extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    /** Turn Screen On and Unlock the keypad when this alert dialog is     displayed */
    getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON |   LayoutParams.FLAG_DISMISS_KEYGUARD);


    /** Creating a alert dialog builder */
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    /** Setting title for the alert dialog */
    builder.setTitle("Alarm");

    /** Setting the content for the alert dialog */
    builder.setMessage("An Alarm by AlarmManager");

    /** Defining an OK button event listener */
    builder.setPositiveButton("OK", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            /** Exit application on click OK */
            getActivity().finish();
        }                       
    });

    /** Creating the alert dialog window */
    return builder.create();
 }

 /** The application should be exit, if the user presses the back button */ 
 @Override
 public void onDestroy() {      
    super.onDestroy();
    getActivity().finish();
 }
}

预约课

  import java.text.DateFormatSymbols;
  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import java.util.GregorianCalendar;

  import android.app.Activity;
  import android.app.AlarmManager;
  import android.app.DatePickerDialog;
  import android.app.Dialog;
  import android.app.Notification;
  import android.app.NotificationManager;
  import android.app.PendingIntent;
  import android.app.TimePickerDialog;
  import android.app.TimePickerDialog.OnTimeSetListener;
  import android.content.Intent;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.DatePicker;
  import android.widget.TimePicker;
  import android.widget.Toast;

 public class Appointment extends Activity {

Button date, time, save;

private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int year;
private int month;
private int day;
int i;
String strmonth, strday, stryear;

String months[] = { "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December" };

int intmonth, intday, intyear, inthour, intminutes;
Calendar c = Calendar.getInstance();
private SimpleDateFormat timeFormatter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.doctor_appointment);

    year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day = c.get(Calendar.DAY_OF_MONTH);

    date = (Button) findViewById(R.id.btnsetdate);
    time = (Button) findViewById(R.id.btnsettime);
    save = (Button) findViewById(R.id.btnsave);
    timeFormatter = new SimpleDateFormat("hh:mm a");
    // c.set(Calendar.MONTH, 4);

    date.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(DIALOG_DATE);
        }
    });
    time.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(DIALOG_TIME);
        }
    });

    save.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent("com.example.healthmanager.DemoActivity");
            /** Creating a Pending Intent */
            PendingIntent operation = PendingIntent.getActivity(
                    getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);

            /** Getting a reference to the System Service ALARM_SERVICE */
            AlarmManager alarmManager = (AlarmManager) getBaseContext()
                    .getSystemService(ALARM_SERVICE);

            String strtime = time.getText().toString();

            Log.v("str btntime", strtime);

            String[] splitstrtime = strtime.split(":");

            Log.v("timestr1", splitstrtime[0]);
            Log.v("timestr2", splitstrtime[1]);

            int splithour = Integer.parseInt(splitstrtime[0]);
            String[] splitsecond = splitstrtime[1].split(" ");

            Log.v("split str second", splitsecond[0]);
            int splitmin = Integer.parseInt(splitsecond[0]);

            /**
             * Creating a calendar object corresponding to the date and time
             * set by the user
             */
            // GregorianCalendar calendar = new
            // GregorianCalendar(year,month,day, hour, minute);
            GregorianCalendar calendar = new GregorianCalendar(intyear,
                    intmonth, intday, splithour, splitmin);

            /**
             * Converting the date and time in to milliseconds elapsed since
             * epoch
             */
            long alarm_time = calendar.getTimeInMillis();

            /** Setting an alarm, which invokes the operation at alart_time */
            alarmManager
                    .set(AlarmManager.RTC_WAKEUP, alarm_time, operation);

            /** Alert is set successfully */
            Toast.makeText(getBaseContext(), "Alarm is set successfully",
                    Toast.LENGTH_SHORT).show();

        }
    });

}

// For date dialog
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DATE:
        return new DatePickerDialog(this, datePickerListener, year, month,
                day);
    case DIALOG_TIME:
        return new TimePickerDialog(this, new OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                c.set(Calendar.HOUR_OF_DAY, hourOfDay);
                c.set(Calendar.MINUTE, minute);
                time.setText(timeFormatter.format(c.getTime()));

            }
        }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false);
    }

    return null;
}

// For date
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year1, int monthOfYear,
            int dayOfMonth) {
        year = year1;
        month = monthOfYear;
        day = dayOfMonth;
        // date.setText(dateFormatter.format(dateTime.getTime()));
        updateDisplay();
    }
};

public String getMonthForInt(int m) {
    String month = "invalid";
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] months = dfs.getMonths();
    if (m >= 0 && m <= 11) {
        month = months[m];
    }
    return month;
}

private void updateDisplay() {
    // String strDOB = month + 1 + "/" + day + "/" + year;
    // Log.v("strDOB : ", strDOB);

    intmonth = month;
    intday = day;
    intyear = year;

    strmonth = Integer.toString(intmonth);
    strday = Integer.toString(intday);
    stryear = Integer.toString(intyear);
    Log.v("month value", strmonth);
    Log.v("day value", strday);
    Log.v("year value", stryear);
    // int one=7;
    // Log.v("string limit",one.length());
    for (i = 0; i < intmonth; i++) {
        String strone = Integer.toString(intmonth);
        strone = months[i];
        // String intmonth=Integer.toString(months);
    }
    Log.v("month value", months[i].toString());
    date.setText(months[i] + "  " + day + "," + year);
}

 }

您可以在
save.setOnClickListener()
中添加对AM和PM的检查,并相应地更改小时值:

save.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        .....

        int splithour = Integer.parseInt(splitstrtime[0]); //10
        String[] splitsecond = splitstrtime[1].split(" "); //40, am

        Log.v("split str second", splitsecond[0]);
        int splitmin = Integer.parseInt(splitsecond[0]); //40

        if(splitsecond[1].equalsIgnoreCase("pm")) {
            splithour += 12;
        } else if(splitsecond[1].equalsIgnoreCase("am") && splithour == 12) {
            splithour = 0;
        }

        ....
    }
}
请使用:-

alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                SystemClock.elapsedRealtime() + alarm_time,
                                operation);
代替

alarmManager.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
阅读:-

SystemClock.elapsedRealtime() is the current time in millis add the total time to skip from now to alarm in millis.

您没有处理上午/下午的事务。只要把这几行代码

int timeDifference=0; 
String ampm=splitampmtime[1]; 
if(ampm.matches("PM")){ 
timeDifference=12; 
} 

int splithour = timeDifference+Integer.parseInt(splitstrtime[0]); 
String[] splitsecond = splitstrtime[1].split(" ");

我使用此方法设置报警:

    /**
     * Set the Alarm
     *
     * @param context  the activity context
     * @param id       the alarm ID for this app
     * @param hour     the alarm hour
     * @param minute   the alarm minute
     * @param timeZone the timezone am = Calendar.AM or pm = Calendar.PM
     */
    public static void setAlarm(Context context, int id, int hour, int minute, int timeZone) {
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.AM_PM, timeZone);

        Intent intent = new Intent(context, PopupActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, id, intent, 0);
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pIntent);
    }

我用了你的逻辑,但可能你不明白我的意思。如果我将闹钟设置为早上7点,我的闹钟将在晚上7点向我显示警报,那么如何清除警报?GregorianCalendar calendar=新的GregorianCalendar(年、月、日、小时、分钟);在这一行中,如果我通过上午7点,则报警不起作用如果我通过下午19点,则报警只对下午有效不对上午有效不知道问题出在哪里我完全理解你的观点,告诉我你通过的splithour小时的值是多少;新的GregorianCalendar(intyear、intmonth、intday、splithour、splitmin);'?如果是7,则将在上午7点调用,但对于值19,将在下午7点调用。。我的代码是根据您在您的案例中要求的AM/PM(2013、1、11、7、20)更改小时值;如果我传递这样的值,我将面临一个问题,即按下“保存”按钮后立即触发报警警报。如果我传递像这个新的GregorianCalendar(2013,1,11,19,20)这样的值,那么它工作得很好,这意味着它不接受am值。我使用了你的代码,它工作的目的是pm,而不是am,因为条件是,如果splithour==12,那么它将转换为零
    /**
     * Set the Alarm
     *
     * @param context  the activity context
     * @param id       the alarm ID for this app
     * @param hour     the alarm hour
     * @param minute   the alarm minute
     * @param timeZone the timezone am = Calendar.AM or pm = Calendar.PM
     */
    public static void setAlarm(Context context, int id, int hour, int minute, int timeZone) {
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.AM_PM, timeZone);

        Intent intent = new Intent(context, PopupActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, id, intent, 0);
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pIntent);
    }