android只执行一次代码

时间:2016-04-06 07:17:02

标签: android alarmmanager

我有一个应用程序,我需要每十五分钟安排一次警报,这是代码

public void scheduleAlarm() {
    // Construct an intent that will execute the AlarmReceiver
    Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
    // Create a PendingIntent to be triggered when the alarm goes off
    final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE,
        intent, PendingIntent.FLAG_UPDATE_CURRENT);
    // Setup periodic alarm every 5 seconds
    long firstMillis = System.currentTimeMillis(); // alarm is set right away
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
    // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
        AlarmManager.INTERVAL_HALF_HOUR, pIntent);
  }
}

我将在mainActivity的onCreate方法中调用此方法,我的问题是我没有得到如何限制只调用一次的方法,因为每次创建活动时都会调用onCreate方法。如果我使用共享首选项来存储方法是否被调用,如果用户从设置中清除appdata,该怎么办。

1 个答案:

答案 0 :(得分:1)

创建一个Prefrence并在其中设置标记。

SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putBoolean("isFlag", false);
                                editor.commit();

在调用此方法之前,请检查标记,如果为true,则调用您的方法。

SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
if (sharedPreferences.getBoolean("isFlag", true)) {
    scheduleAlarm();
}

我希望它可以帮助你...