开发者

how do i set an alarm manager to fire every on specific day of week and time in android?

开发者 https://www.devze.com 2023-02-23 07:47 出处:网络
for example i want to have an alarm that will fire every sunday at noon.... how would i do 开发者_如何学JAVAthis?Use the AlarmManager class:

for example i want to have an alarm that will fire every sunday at noon.... how would i do 开发者_如何学JAVAthis?


Use the AlarmManager class:

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

Class Overview

This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

Use public void set (int type, long triggerAtTime, PendingIntent operation) to set the time to fire it.

Use void setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) to schedule a repeating alarm.

Here's a full example. I don't really remember all the Calendar methods, so I'm sure that part can be streamlined, but this is a start and you can optimize it later:

AlarmManager alarm = (AlarmMAnager) Context.getSystemService(Context.ALARM_SERVICE);
Calendar timeOff = Calendar.getInstance();
int days = Calendar.SUNDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)); // how many days until Sunday
timeOff.add(Calendar.DATE, days);
timeOff.set(Calendar.HOUR, 12);
timeOff.set(Calendar.MINUTE, 0);
timeOff.set(Calendar.SECOND, 0);

alarm.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), yourOperation);


finally this right solution if set as (sun,tus ,fri) you must create three alarm for these three day the following code set alarm every sunday and send dayOfWeek=1;

 public void setAlarm_sun(int dayOfWeek) {
     cal1.set(Calendar.DAY_OF_WEEK, dayOfWeek);
     Toast.makeText(getApplicationContext(), "sun "+cal1.get(Calendar.DAY_OF_WEEK), 222).show();

     Toast.makeText(getApplicationContext(), "Finsh", 222).show();

        Intent intent = new Intent(this, SecActivity.class);
        PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0,
                intent, 0);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 12345,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

         Long alarmTime = cal1.getTimeInMillis();
         AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);

       // am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime,7* 24 * 60 * 60 * 1000 , pendingIntent);
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime,7* 24 * 60 * 60 * 1000 , pendingIntent);

} 
0

精彩评论

暂无评论...
验证码 换一张
取 消