2013-06-03 14 views
14

Jestem nowy na Androida. Pracuję nad aplikacją, w której muszę zaplanować zadanie, które będzie wykonywane w przyszłości.Jak zaplanować zadanie za pomocą Menedżera alarmów

Przeczytałem o aplikacji AlarmManager i dowiedziałem się, że możemy to zrobić za pomocą aplikacji AlarmManager.

Czy ktoś może mi powiedzieć o jakimś tutorialu lub o jakimkolwiek źródle, w którym mogę uzyskać rzeczy.

Odpowiedz

25

zawartość pochodzi z blogu Scheduling Task Using Alarm Manager in Android

public void scheduleAlarm(View v) 
{ 
    // The time at which the alarm will be scheduled. Here the alarm is scheduled for 1 day from the current time. 
    // We fetch the current time in milliseconds and add 1 day's time 
    // i.e. 24*60*60*1000 = 86,400,000 milliseconds in a day.  
    Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000; 

    // Create an Intent and set the class that will execute when the Alarm triggers. Here we have 
    // specified AlarmReceiver in the Intent. The onReceive() method of this class will execute when the broadcast from your alarm is received. 
    Intent intentAlarm = new Intent(this, AlarmReceiver.class); 

    // Get the Alarm Service. 
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

    // Set the alarm for a particular time. 
    alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT)); 
    Toast.makeText(this, "Alarm Scheduled for Tomorrow", Toast.LENGTH_LONG).show();  
} 

AlarmReceiver Klasa

public class AlarmReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 

     // Your code to execute when the alarm triggers 
     // and the broadcast is received. 

    } 
} 
+0

robi powyższy kod oznacza, że ​​alarm będzie wykonać zadanie, jeśli zostanie wykryty nowy dzień? – Sen

+0

@Baras: wykonuje dokładnie 24 godziny po uruchomieniu, co jest nieco inne. W rzeczywistości może to być dwa razy w tym samym dniu, jeśli ma się to dokładnie w przypadku oszczędności w ciągu dnia. –

+0

Ten kod nie działa, jeśli aplikacja nie jest w tle. Proszę pomóc! – Sidhartha

1

pobrać Service Alarm i Set Alarm:

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT); 

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

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent); 

U potrzebują broadcastreceiver że otrzyma to wydarzenie

class Alarmreceiver extends Broadcastreceiver 
{ 
    //u can to task in onreceive method of receiver. 
} 

nie zapomnij zarejestrować odbiornik w Androidmanifest złożyć Nadzieja To Ci pomaga.

Powiązane problemy