android 只执行一次代码
android execute code only once
我有一个应用程序,我需要每十五分钟安排一次闹钟,这是代码
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();
}
希望对你有所帮助...
我有一个应用程序,我需要每十五分钟安排一次闹钟,这是代码
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();
}
希望对你有所帮助...