在android中实现闹钟定时

时间:2014-01-27 13:25:18

标签: android

我想在我的应用程序中实现警报功能。所以不知道如何设置确切的警报时间这是我的代码。当我试图设置警报时间然后它没有在确切的时间触发请给我任何想法......

public class Settingscreen extends Activity {
long difference;
int Curenthour;
int currentminute;
int Hourdiffrence;
int Minutedifference;
int MinutedifferencePositive;
int HourdifferencePositive;
CheckBox Checkboxtimeenable;
private int hour;
private int minute;
private int year;
private int month;
private int day;
TextView TvSettime;
SQLiteDatabase sampleDB;
Button BtnChangetime;
static final int DATE_PICKER_ID1 = 1111;
static final int TIME_DIALOG_ID = 999;
Cursor localCursor = null;
String cursorvalue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_settingscreen);

    BtnChangetime = (Button) findViewById(R.id.button1);
    TvSettime = (TextView) findViewById(R.id.textView6);
    Checkboxtimeenable = (CheckBox) findViewById(R.id.checkBox1);
    TvSettime.setText("18:00");

    BtnChangetime.setEnabled(false);
    try {
        this.sampleDB = openOrCreateDatabase("questionbook", 0, null);

        Settingscreen.this.sampleDB
                .execSQL("CREATE TABLE if not exists Temp(Time     VARCHAR);");

        localCursor = this.sampleDB.rawQuery("select Time from Temp", null);

        if (localCursor.getCount() > 0) {

            boolean bool = localCursor.moveToFirst();

            if (localCursor.moveToFirst()) {
                do {

                    TvSettime.setText(localCursor.getString(0));

                    Checkboxtimeenable.setChecked(true);
                    BtnChangetime.setEnabled(true);
                } while (localCursor.moveToNext());
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
    Checkboxtimeenable
            .setOnCheckedChangeListener(new OnCheckedChangeListener() {
                int i1;
                int i2;
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    // TODO Auto-generated method stub
                    if (Checkboxtimeenable.isChecked()) {
                        BtnChangetime.setEnabled(true);
                        String dtStart = TvSettime.getText().toString();

                        Settingscreen.this.sampleDB
                                .execSQL("INSERT INTO Temp Values ('"
                                        + dtStart + "');");
                        SimpleDateFormat format = new SimpleDateFormat(
                                "HH:mm");
                        try {
                            Date date = format.parse(dtStart);
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(date);
                             i1 = cal.getTime().getHours();
                             i2 = cal.getTime().getMinutes();
                            long convertedLong = cal.getTimeInMillis();
                            long currentTimeLong = System
                                    .currentTimeMillis();
                            Calendar now = Calendar.getInstance();

                            System.out.println("Current time : "
                                    + now.get(Calendar.HOUR_OF_DAY) + ":"
                                    + now.get(Calendar.MINUTE) + ":"
                                    + now.get(Calendar.SECOND));

                            Curenthour = now.get(Calendar.HOUR_OF_DAY);
                            currentminute = now.get(Calendar.MINUTE);
                            Hourdiffrence = Curenthour - i1;
                            Minutedifference = currentminute - i2;
                            MinutedifferencePositive = Math
                                    .abs(Minutedifference);
                            HourdifferencePositive = Math
                                    .abs(Hourdiffrence);
                            System.out.println("Positive number : "
                                    + Math.abs(Hourdiffrence));
                            System.out.println("Positive minute : "
                                    + Math.abs(Minutedifference));
                            System.out.println("Time before 50 minutes : "
                                    + now.get(Calendar.HOUR_OF_DAY) + ":"
                                    + now.get(Calendar.MINUTE) + ":"
                                    + now.get(Calendar.SECOND));

                            String strDiff = String.valueOf(difference);
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        if (Curenthour > i1) {

                            Hourdiffrence = 24 - (Curenthour - i1);
                            Minutedifference = currentminute - i2;
                            MinutedifferencePositive = Math
                                    .abs(Minutedifference);
                            HourdifferencePositive = Math
                                    .abs(Hourdiffrence);

                        } else if (Curenthour < i1) {

                            Hourdiffrence = Curenthour - i1;
                            Minutedifference = currentminute - i2;
                            MinutedifferencePositive = Math
                                    .abs(Minutedifference);
                            HourdifferencePositive = Math
                                    .abs(Hourdiffrence);
                        }

                        if (HourdifferencePositive == 0) {

                            Intent intentAlarm = new Intent(
                                    Settingscreen.this, AlarmReciever.class);

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

                            alarmManager.set(
                                    AlarmManager.RTC_WAKEUP,
                                    System.currentTimeMillis()
                                            + MinutedifferencePositive * 60
                                            * 1000,
                                    PendingIntent
                                            .getBroadcast(
                                                    Settingscreen.this,
                                                    1,
                                                    intentAlarm,
                                                    PendingIntent.FLAG_UPDATE_CURRENT));
                            Toast.makeText(Settingscreen.this,
                                    "Alarm Scheduled @" + dtStart,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Intent intentAlarm = new Intent(
                                    Settingscreen.this, AlarmReciever.class);

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

                            alarmManager.set(
                                    AlarmManager.RTC_WAKEUP,
                                    System.currentTimeMillis()
                                            + HourdifferencePositive
                                            * MinutedifferencePositive * 60
                                            * 1000,
                                    PendingIntent
                                            .getBroadcast(
                                                    Settingscreen.this,
                                                    1,
                                                    intentAlarm,
                                                    PendingIntent.FLAG_UPDATE_CURRENT));
                            Toast.makeText(Settingscreen.this,
                                    "Alarm Scheduled @" + dtStart,
                                    Toast.LENGTH_LONG).show();

                        }
                    } else {
                        /*
                         * String where = "Time = 'dtStart'";
                         * 
                         * String[] whereArgs = null; String table_name =
                         * "Temp"; sampleDB.delete(table_name, where,
                         * whereArgs);
                         */
                        sampleDB.execSQL("drop table if exists Temp");
                        Toast.makeText(Settingscreen.this,
                                "Alarm cancelled", Toast.LENGTH_LONG)
                                .show();
                        Intent intentAlarm = new Intent(Settingscreen.this,
                                AlarmReciever.class);

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

                        alarmManager.set(AlarmManager.RTC_WAKEUP,
                                System.currentTimeMillis()
                                        + MinutedifferencePositive * 60
                                        * 1000, PendingIntent.getBroadcast(
                                        Settingscreen.this, 1, intentAlarm,
                                        PendingIntent.FLAG_CANCEL_CURRENT));
                        BtnChangetime.setEnabled(false);
                    }

                }
            });

    BtnChangetime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(TIME_DIALOG_ID);
            long currentTimeLong = System.currentTimeMillis();
        }
    });

}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_PICKER_ID1:

        // open datepicker dialog.
        // set date picker for current date
        // add pickerListener listner to date picker
        DatePickerDialog d = new DatePickerDialog(this, pickerListener,
                year, month, day);
        Calendar cal = Calendar.getInstance();
        // cal.set(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH)+2,cal.get(Calendar.DAY_OF_MONTH),
        // cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), 0);
        long time = cal.getTimeInMillis();
        // d.getDatePicker().setMaxDate(time);
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH),
                cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), 0);
        time = cal.getTimeInMillis();

        return d;

        // return new DatePickerDialog(this, pickerListener, year, month,
        // day);
    case TIME_DIALOG_ID:

        return new TimePickerDialog(this, myTimeSetListener, hour, minute,
                false);

    default:

    }
    return null;
}

private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    @SuppressWarnings("deprecation")
    @Override
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {

        // Show selected date

        SimpleDateFormat smpledtf = new SimpleDateFormat("MM-dd-yyy");
    }
};
private TimePickerDialog.OnTimeSetListener myTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // TODO Auto-generated method stub

        int i1 = 0;
        int i2 = 0;
        String time = String.valueOf(hourOfDay) + ":"
                + String.valueOf(minute);
        TvSettime.setText(time);

        Settingscreen.this.sampleDB.execSQL("INSERT INTO Temp Values ('"
                + time + "');");
        Time today = new Time(Time.getCurrentTimezone());
        today.setToNow();

        Intent intentAlarm = new Intent(Settingscreen.this,
                AlarmReciever.class);

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

        alarmManager.set(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + MinutedifferencePositive * 60
                        * 1000, PendingIntent.getBroadcast(
                        Settingscreen.this, 1, intentAlarm,
                        PendingIntent.FLAG_CANCEL_CURRENT));
        String dtStart = TvSettime.getText().toString();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        try {
            Date date = format.parse(dtStart);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            i1 = cal.getTime().getHours();
            System.out.println("alarm hour :"+ i1);
             i2 = cal.getTime().getMinutes();
            long convertedLong = cal.getTimeInMillis();
            long currentTimeLong = System.currentTimeMillis();
            Calendar now = Calendar.getInstance();

            System.out.println("Current time : "
                    + now.get(Calendar.HOUR_OF_DAY) + ":"
                    + now.get(Calendar.MINUTE) + ":"
                    + now.get(Calendar.SECOND));

            /*
             * now.add(Calendar.MINUTE,i2);
             * 
             * System.out.println("New time after adding 20 minutes : " +
             * now.get(Calendar.HOUR_OF_DAY) + ":" +
             * now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
             */

            // now = Calendar.getInstance();
            // now.add(Calendar.HOUR, -i1);
            Curenthour = now.get(Calendar.HOUR_OF_DAY);
            System.out.println("current hour :"+ Curenthour);
            currentminute = now.get(Calendar.MINUTE);
            Hourdiffrence = Curenthour - i1;
            Minutedifference = currentminute - i2;
            MinutedifferencePositive = Math.abs(Minutedifference);
            HourdifferencePositive = Math.abs(Hourdiffrence);
            System.out.println("Positive number : "
                    + Math.abs(Hourdiffrence));
            System.out.println("Positive minute : "
                    + Math.abs(Minutedifference));
            System.out.println("Time before 50 minutes : "
                    + now.get(Calendar.HOUR_OF_DAY) + ":"
                    + now.get(Calendar.MINUTE) + ":"
                    + now.get(Calendar.SECOND));

            String strDiff = String.valueOf(difference);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (i1 > Curenthour) {

            Hourdiffrence = 24 - (Curenthour - i1);
            Minutedifference = currentminute - i2;
            MinutedifferencePositive = Math
                    .abs(Minutedifference);
            HourdifferencePositive = Math
                    .abs(Hourdiffrence);

        } else if (Curenthour > i1) {

            Hourdiffrence = Curenthour - i1;
            Minutedifference = currentminute - i2;
            MinutedifferencePositive = Math
                    .abs(Minutedifference);
            HourdifferencePositive = Math
                    .abs(Hourdiffrence);
        }
        if (HourdifferencePositive == 0) {

            Intent intentAlarm2 = new Intent(Settingscreen.this,
                    AlarmReciever.class);

            AlarmManager alarmManager2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            alarmManager.set(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + MinutedifferencePositive
                            * 60 * 1000, PendingIntent.getBroadcast(
                            Settingscreen.this, 1, intentAlarm,
                            PendingIntent.FLAG_UPDATE_CURRENT));
            Toast.makeText(Settingscreen.this,
                    "Alarm Scheduled @" + dtStart, Toast.LENGTH_LONG)
                    .show();
        } else {
            Intent intentAlarm2 = new Intent(Settingscreen.this,
                    AlarmReciever.class);

            AlarmManager alarmManager2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            alarmManager
                    .set(AlarmManager.RTC_WAKEUP,
                            System.currentTimeMillis()
                                    + HourdifferencePositive
                                    * MinutedifferencePositive * 60 * 1000,
                            PendingIntent.getBroadcast(Settingscreen.this,
                                    1, intentAlarm,
                                    PendingIntent.FLAG_UPDATE_CURRENT));
            Toast.makeText(Settingscreen.this,
                    "Alarm Scheduled @" + dtStart, Toast.LENGTH_LONG)
                    .show();

        }
    }
};

}

1 个答案:

答案 0 :(得分:0)

来自http://developer.android.com/reference/android/app/AlarmManager.html

  

注意:从API 19(KITKAT)开始,警报传递是不准确的:操作系统   将移动警报以最小化唤醒和电池使用。那里   是支持需要严格交付的应用程序的新API   担保;请参阅setWindow(int,long,long,PendingIntent)和   setExact(int,long,PendingIntent)。应用程序   targetSdkVersion早于API 19将继续看到   以前的行为,其中所有警报都在何时传递   请求。