Intent intent = new Intent(TasksActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(TasksActivity.this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
这段代码被我放在activity的onCreate方法中。
在(TasksActivity.this, AlarmReceiver.class)中TasksActivity为当前activity,AlarmReceiver.class为一个广播接收器,从代码上看是接收一个系统服务的广播
AlarmReceiver的代码如下:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "滴滴!时间到", Toast.LENGTH_SHORT).show();
}
}
执行的结果是,启动activity10秒后,系统提示时间到。启动activity马上关闭,仍然会在10秒后产生提示