关于 Android 中的 AlarmManager
About AlarmManager in Android
我知道通过使用 AlarmManager,您可以在特定时间启动服务,并且要注册警报,您需要在 activity 的 "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 只是一个 class 扩展服务。
The problem is, the "onCreate" method will be called every time the application is opened
要回答这个问题,如果你的警报是针对 activity 的,那么它就无法避免。如果您打算在您的应用程序启动时注册警报(不是非常具体 activity),您仍然可以减轻它。您可以在 Application#onCreate
中设置闹钟,而不是在 activity 中注册闹钟
我知道通过使用 AlarmManager,您可以在特定时间启动服务,并且要注册警报,您需要在 activity 的 "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 只是一个 class 扩展服务。
The problem is, the "onCreate" method will be called every time the application is opened
要回答这个问题,如果你的警报是针对 activity 的,那么它就无法避免。如果您打算在您的应用程序启动时注册警报(不是非常具体 activity),您仍然可以减轻它。您可以在 Application#onCreate