2016-02-29 62 views
0
Calendar calendar = Calendar.getInstance(); 

      calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // Tue, Wed... 
      calendar.set(Calendar.HOUR_OF_DAY, 1); 
      calendar.set(Calendar.MINUTE, 0); 
      calendar.set(Calendar.SECOND, 0); 
      PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT); 
      AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
      am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 7*24*60*60*1000, pi); 

這一週將閃光一次重複在週一,但: 我想設置報警意向未決只在工作日(不含週六,週日),如何只用一個意圖辦呢? 我不想使用5個不同的PendingIntents與5個不同的ID,因爲那麼我必須取消5報警僅在工作日

回答

1

可能:

創建setAlarm方法:

public void setAlarm(long interval){ 
    Calendar calendar = Calendar.getInstance(); 

    //Alarm will go off at 1 
    calendar.set(Calendar.HOUR_OF_DAY, 1); 
    calendar.set(Calendar.MINUTE, 0); 
    calendar.set(Calendar.SECOND, 0); 

    PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pi); 
} 

創建cancelAlarm方法(可選,如果你想在某個地方使用它) :

public void cancelAlarm(Context context){ 
    PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    am.cancel(pi); 
} 

檢查當天在onReceive()

@Override 
public void onReceive(Context context, Intent intent) { 

    Calendar calendar = Calendar.getInstance(); 
    int day = calendar.get(Calendar.DAY_OF_WEEK); //Sunday = 1, Saterday = 7 
    switch(day){ 

     case 6: //Friday 
      long interval = 3*24*60*60*1000 //skip saterday and sunday 
      setAlarm(interval); 

     case 2: //Monday 
      setAlarm(AlarmManager.INTERVAL_DAY); //Alarm will repeat everyday, until friday 
     break; 
} 

PS:不要忘了使用的地方設置鬧鐘爲第一時間:setAlarm(AlarmManager.INTERVAL_DAY);

我認爲這應該工作。

1

將日曆設置爲多個日期是不可能的,因此您無法按照自己的喜好進行操作。

我建議你做的事情是每天重複鬧鐘,並在onReceive中檢查它是哪一天,如果是星期六/星期日就馬上回來,不要做任何事情。

Calendar calendar = Calendar.getInstance(); 

calendar.set(Calendar.HOUR_OF_DAY, 1); 
calendar.set(Calendar.MINUTE, 0); 
calendar.set(Calendar.SECOND, 0); 
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyClass.class), 0); 
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pi); 

接收機

public class MyClass extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (today == sunday || today == saturday) { 
      return; 
     } 

     // do normal stuff. 
    } 
} 
+0

謝謝,會試試這個方法,看起來很簡單:) –