【问题标题】:About AlarmManager in Android关于Android中的AlarmManager
【发布时间】: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


    【解决方案1】:

    The problem is, the "onCreate" method will be called every time the application is opened 要回答这个问题,如果您的警报是针对该活动的,那么它是无法避免的。如果您的意图是在您的应用程序启动时注册警报(不是非常具体的活动),您仍然可以减轻它。不用在activity中注册闹钟,可以在Application#onCreate中设置闹钟

    【讨论】:

      猜你喜欢
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多