【发布时间】:2017-02-14 11:06:26
【问题描述】:
我知道通过使用AlarmManager,您可以在特定时间启动服务,并且要注册警报,您需要在活动的“onCreate”方法中进行设置。问题是,每次打开应用程序时都会调用“onCreate”方法,因此实际上会一次又一次地设置警报。 Java 和 Android 是否有一些自动机制来避免这种重复设置?
public class MyActivity extends Activity {
...
MyAlarmReceiver alarm = new MyAlarmReceiver();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// this set the alarm for message notification
alarm.setAlarm(this);
}
...
}
和,
public class MyAlarmReceiver extends WakefulBroadcastReceiver {
...
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, service);
// END_INCLUDE(alarm_onreceive)
}
public void setAlarm(Context context) {
// This intent is used in alarm
Intent intent = new Intent(context.getApplicationContext(), MyAlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
PendingIntent pIntent = PendingIntent.getBroadcast(context, reqCode, intent, PendingIntent.FLAG_ONE_SHOT);
... //Set the alarm
}
}
而 MyService 只是一个扩展 Service 的类。
【问题讨论】:
标签: java android alarmmanager