2016-01-17 3 views
0

Я пытаюсь создать планировщик, который даст вам уведомление, когда запланированная дата и время наступят. Я использую класс вещательного приемника, и я заставил его работать на день.Планировщик в Android на определенную дату

Это означает, что вы можете выбрать любой день и время в течение месяца, он будет работать нормально, но у меня много проблем, если пользователь выбирает следующий месяц или год. Вот мой код по расписанию нажмите кнопку.

Здесь mDay, mMonth, mYear, mHour, mMinute - это выбранная дата и время пользователя для его активности и cday, cmonth, cyear - текущая дата и время.

btn_schedule.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      System.out.println("Entered in Alarm on click"); 

      Calendar cal = Calendar.getInstance(); 
      Hour = cal.get(Calendar.HOUR_OF_DAY); 
      Minute = cal.get(Calendar.MINUTE); 

      cday = cal.get(Calendar.DATE); 
      cmonth = cal.get(Calendar.MONTH); 
      cyear = cal.get(Calendar.YEAR); 

      dday = mDay - cday; 
      dmonth = mMonth - cmonth; 
      dyear = mYear - cyear; 

      if (dyear == 0) { 
       if (dmonth == 0) { 
        if (dday == 0) { 
         long CurrentMilli = (mHour * 3600 * 1000) + (mMinute * 60 * 1000); 
     long SelectedMilli = (Hour * 3600 * 1000) + (Minute * 60 * 1000); 

     long diff = CurrentMilli - SelectedMilli; 
     diff1 = diff; 
     System.out.println("difference and " + diff + "diff1" + diff1); 

     new CountDownTimer(diff, 1000) { // adjust the 
      // milli 
      // seconds 
      // here 

      public void onTick(long millisUntilFinished) { 
      } 

      public void onFinish() { 
      } 
     }.start(); 
    } 

        } else {// Else if day is not the same 
         int dh = 24 - Hour; // today's remaining hours till 
              // next date 
         int dm = 60 - Minute;// today's remaining minutes 
               // till next date 
         long dhm = dh * 3600000;// in milli 
         long dmm = dm * 60000;// in milli 
         long totaltm = dhm + dmm; 
         diff1 = totaltm; 
         long lh = mHour * 3600000;// selected hours in milli 
         long lm = mMinute * 60000;// selected min in milli 
         ltt = lh + lm; 

         new CountDownTimer(totaltm, 1000) { // adjust the 
          // milli 
          // seconds 
          // here 

          public void onTick(long millisUntilFinished) { 
          } 

          public void onFinish() { 
           dday--; 
           forDay1(dday); 
          } 
         }.start(); 

        } 
       } else { 
        // Else if month is not the same 



       } 

      } else {// Else if year is not the same 

      } 
      long a = diff1; 
      Long alertTime = new GregorianCalendar().getTimeInMillis() + a; 
      Intent alertIntent = new Intent(HomeScreen.this, Alerts.class); 
      AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
      am.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent 
        .getBroadcast(HomeScreen.this, 2, alertIntent, 
          PendingIntent.FLAG_UPDATE_CURRENT)); 
      System.out.println("Notification is called"); 
      Intent moreinfo = new Intent(HomeScreen.this, HomeScreen.class); 
      TaskStackBuilder tsb = TaskStackBuilder 
        .create(getApplicationContext()); 
      tsb.addParentStack(HomeScreen.class); 
      tsb.addNextIntent(moreinfo); 



     } 
    }); 

Вот мой Broadcast класс:

public class Alerts extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     System.out.println("Inside Service"); 
     createNotification(context, "Times Up!", "Start Your Activity!", 
       "Click here to enter the application!"); 

    } 

    public void createNotification(Context context, String msg, String msgtext, 
      String msgalert) { 
     System.out.println("Method inside service is called"); 
     PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(
       context, HomeScreen.class), 0); 
     NotificationCompat.Builder ncb = new NotificationCompat.Builder(context) 
       .setContentTitle(msg).setContentText(msgtext) 
       .setTicker(msgalert).setSmallIcon(R.drawable.ic_launcher) 
       .setDefaults(Notification.DEFAULT_SOUND) 
       .setDefaults(Notification.DEFAULT_VIBRATE); 

     ncb.setContentIntent(pi); 
     ncb.setAutoCancel(true); 

     NotificationManager nm = (NotificationManager) context 
       .getSystemService(Context.NOTIFICATION_SERVICE); 
     nm.notify(2, ncb.build()); 

    } 

} 

И этот код работает на любой день в течение месяца.

ответ

1

Вам не нужно делать все, что заказные логические вычисления различия ddat и большой if (dyear == 0) { ... Просто установите выбранные пользователем поля в Calendar:

Calendar cal = Calendar.getInstance(); 
cal.set(mYear, mMonth, mDay, mHour, mMinute); 

И тогда вы можете использовать временную метку нового календаря в качестве времени оповещения.

long alertTime = cal.getTimeInMillis(); 
+0

спасибо, приятель !! Со временем мне очень понравилось –

Смежные вопросы