2014-01-27 69 views
3

我想在我的app.so中實現鬧鐘功能不知道如何設置鬧鐘的確切時間這是我的代碼當我嘗試設置鬧鐘時間時,它不會在確切的時間觸發請給我任何的想法......在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(); 

     } 
    } 
}; 

}

回答

0

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

注:與API開始19(奇巧)警報傳遞不精確:操作系統 將小號爲了最大限度地減少喚醒和電池使用,提醒警報。有 是新的API來支持需要嚴格交付 保證的應用程序;請參閱setWindow(int,long,long,PendingIntent)和setExact(int,long,PendingIntent)。其中 targetSdkVersion早於API 19的應用程序將繼續看到 之前的行爲,在該行爲中, 請求時所有報警均準確傳送。