gpt4 book ai didi

android 只执行一次代码

转载 作者:行者123 更新时间:2023-11-30 01:25:44 25 4
gpt4 key购买 nike

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

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 方法中调用此方法,我的问题是我不知道如何限制只调用一次的方法,因为每次创建 Activity 时都会调用 onCreate 方法。如果我使用 sharedpreference 来存储该方法是否被调用,如果用户从设置中清除 appdata 该怎么办。

最佳答案

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

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

在调用这个方法之前检查他的标志,如果是真的那么你的方法将被调用。

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

希望对你有帮助...

关于android 只执行一次代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36444052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com