的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下面的答案可能是你正在寻找的。 –