android只执行一次代码
我有一个应用程序,我需要计划每15分钟报警这是代码android只执行一次代码,android,alarmmanager,Android,Alarmmanager,我有一个应用程序,我需要计划每15分钟报警这是代码 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
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方法。如果我使用SharedReference来存储是否调用了该方法,那么如果用户从设置中清除appdata,该怎么办。创建一个Preference并在其中设置标志
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isFlag", false);
editor.commit();
在调用此方法之前,请检查he标志,如果它为真,则将调用您的方法
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
if (sharedPreferences.getBoolean("isFlag", true)) {
scheduleAlarm();
}
我希望它可以帮助你…如果用户清除了应用程序数据,即使谷歌也帮不了你;希望你得到答案:);玩得高兴coding@Shantanu嗨,请检查一下这个问题。然后将信息存储在本地数据库中。没有确定的方法可以解决这个问题。如果用户清除prefs,它将再次触发。此外,根用户也可以清除数据库,但这会减少可能的用户。如果您真的希望每个用户只执行一次代码,则可以从联机服务器(登录)中提取计数器,并使用此计数器仅触发代码一次。您可以创建自己的活动,如RestrictClearData.java,并在此活动中设置错误消息,如。。“您没有清除应用程序数据的权限”只需在清单文件的应用程序标记中添加一行即可。android:manageSpaceActivity=“.RestrictClearData”“将出现“管理空间”按钮,而不是“清除数据”按钮。如果用户单击此按钮,则限制用户活动将调用。我希望它能帮助你……)好吧。。如果你问这个问题,那么你可以接受我的回答。你也可以提高你的声誉来接受我的回答。