的AlarmManager類允許重複報警的調度是 會在未來的設定點運行。警報管理器會給定一個 PendingIntent以在計劃警報時觸發。當觸發警報 時,已註冊的意圖由Android系統廣播, 在目標應用程序尚未運行時啓動。
創建從廣播接收器繼承的類。在BroadcastReceiver接收Intent廣播時調用的onReceive方法中,我們將設置運行我們任務的代碼。
AlarmReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// For our recurring task, we'll just display a message
Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
}
}
然後我們需要在清單文件中註冊的BroadcastReceiver。在清單文件中聲明AlarmReceiver。
<application>
.
.
<receiver android:name=".AlarmReceiver"></receiver>
.
.
</application>
在您的調用Activity中包含以下實例變量。
private PendingIntent pendingIntent;
private AlarmManager manager;
在的onCreate(),我們創建一個引用我們的廣播接收器類,並用它在我們的PendingIntent的意圖。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Retrieve a PendingIntent that will perform a broadcast
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
}
然後,我們包括將設置循環報警的方法。一旦設置,鬧鐘將在每X時間後觸發,這裏我們需要10秒的時間,例如,您可以簡單地計算這個值,以便每天觸發它。
public void startAlarm(View view) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
接下來,我們還將設置cancelAlarm()方法來停止警報,如果需要的話。
public void cancelAlarm(View view) {
if (manager != null) {
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
}
在一個答案[此鏈接](http://stackoverflow.com/a/8801990/3800164)會幫你安排在未來的任務。 –
我的理解是,如果你的應用程序要退出_before_任務被產生,那麼不會,它不會執行。如果您的應用嘗試退出_while_任務正在運行,則操作系統可能會阻止它。 @jitesh下面的答案可能是你正在尋找的。 –