2013-06-03 25 views
14

Tôi mới sử dụng Android. Tôi đang làm việc trên một ứng dụng mà tôi cần phải lên lịch một nhiệm vụ sẽ được thực hiện trong tương lai.Cách lên lịch một tác vụ bằng Trình quản lý báo thức

Tôi đã đọc về AlarmManager và biết rằng chúng tôi có thể thực hiện việc này bằng AlarmManager.

Bất cứ ai có thể vui lòng cho tôi biết về một số hướng dẫn hoặc bất kỳ nguồn nào mà tôi có thể nhận được mọi thứ.

Trả lời

25

Nội dung lấy từ Blog 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 Lớp

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

hiện các mã trên có nghĩa là báo động sẽ thực hiện nhiệm vụ nếu ngày mới được phát hiện? – Sen

+0

@Baras: nó thực thi chính xác 24 giờ sau khi nó được kích hoạt, điều này hoàn toàn khác biệt. Trong thực tế, có thể là hai lần trong cùng một ngày, nếu nó xảy ra vừa phải trong tiết kiệm ánh sáng ban ngày. –

+0

Mã này không hoạt động nếu ứng dụng không ở chế độ nền..Xin vui lòng trợ giúp !! – Sidhartha

1

Dịch vụ báo thức get và set báo thức:

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 cần một broadcastreceiver rằng sẽ nhận được sự kiện này

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

Dont quên đăng ký nhận này trong Androidmanifest nộp Hope Điều này giúp bạn.

Các vấn đề liên quan