有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java关于Android中的AlarmManager

我知道,通过使用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只是一个扩展服务的类


共 (1) 个答案

  1. # 1 楼答案

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