android - 在 OnSharedPreferenceChangeListener() 中使用 commit()

标签 android performance persistence sharedpreferences

我正在使用 OnSharedPreferenceChangeListener():

listener=new SharedPreferences.OnSharedPreferenceChangeListener() {

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        if(key.equals("TIME"))
        {
            Log.v("Tagger","Value has changed");
            long L=-2;
            if(sharedPreferences.contains("TIME"))
            {
                L=sharedPreferences.getLong("TIME", 0);
                long  HH=(L/1000)/3600; 
                long MM=((L/1000)/60)%60;
                long SS=(L/1000)%60;
                MILLIS-=1000;
                mainHH.setText(Long.toString(HH));
                mainMM.setText(Long.toString(MM));
                mainSS.setText(Long.toString(SS));
            }
            if(L<=0)
            {
                Editor edit=sharedPreferences.edit();
                edit.remove("TIME");
                edit.commit();

                Log.v("VALUE",Long.toString(454L));
                Intent intent = new Intent(getApplicationContext(), TimerAlarmReceiver.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                TimerAlarmReceiver.alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                TimerAlarmReceiver.alarmMgr.cancel(pendingIntent);
                start.setText("Start the Test?");
                TimerOn=false;

                edit.putBoolean("TimerOn", TimerOn);
                edit.commit();          
            }
        }
    }
};
sharedPreferences.registerOnSharedPreferenceChangeListener(listener);

不将对 commit 的调用放在监听器中是合乎逻辑的,因为它会变得递归并导致 StackOverflow。但我不明白的是为什么这段代码在更高版本的 android 上运行良好(在 >4.X 上测试)。但是当我在 android 2.3 上使用它时,它会导致预期的错误。

我如何:

  1. 让它在旧版本的 android 上运行 或者
  2. 添加一个异常,当我在其中调用 commit() 时不触发监听器?

最佳答案

您始终可以通过使用基本情况 来避免无限循环问题的递归。 base case 的功能是在您的应用达到特定的预定义状态时停止递归。

在您的情况下,您可以使用以下解决方案之一:

1) 当您的跳过条件发生时取消注册 OnSharedPreferenceChangeListener

sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener);

2) 在你的 class 中创建一个全局 bool 值 flag 并在 OnSharedPreferenceChangeListener 中执行你的逻辑之前检查它并用 设置它>false 当您达到您的基本情况

private boolean changesFlag = true; 

关于android - 在 OnSharedPreferenceChangeListener() 中使用 commit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25218934/

相关文章:

ios - 在 iPod Touch/iPhone Objective-C 中保存数据的最佳方式

android - 不确定这里是否需要 WakeLock

java - 向 TextView 添加一个字母

android - 在Android Canvas中快速绘制大量线条: dealing with antialiasing and KitKat's peculiarities

ruby-on-rails - 如何为亚马逊 s3 图像添加过期标题?

javascript - 我的日期选择器工作得不太好

java - JPA : OpenJPA : The id class specified by type does not match the primary key fields of the class

android - 从历史记录中删除 "start"- Activity

javascript - 使用自定义绑定(bind)、扩展器或自定义函数扩展 Knockout

json - Swift:无法使用 'decode' 类型的参数列表调用 '([Idea], from: Data)'