android - 重复使用 Android Shared Preference 存储会影响性能吗?

标签 android sharedpreferences android-sharedpreferences

我的应用程序使用 Android 服务中的 LocationListener 来频繁更新位置。应用程序将一些与位置过滤器相关的数据存储在共享首选项中。要求是尽可能频繁地更新位置。 我从监听器的 onLocationChanged 中的共享首选项中检索数据。 这是我的代码

public class MyLocationListener implements LocationListener {
    public void onLocationChanged(final Location loc) {
        sharedPreferences =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        int filterOne = sharedPreferences.getInt("filter_data",100);
        ------
        ------
        //code to process location with filter   
        ------
        ------ 
    }
}

使用上面的代码,sharedPreference 以重复的方式使用。

我已经尝试将过滤器变量放在 onLocationChanged 之外,但是当服务重新启动时,值丢失并设置为零。

我只想知道这种做法好不好? 我应该使用其他选项吗?

最佳答案

Using above code sharedPreference is used in repetitive manner. I just want to know is that good practice or not?

以重复的方式访问 SharedPreferences 是没有问题的。但是,在您的情况下,每次事件触发时您都会重新初始化 sharedPreferences 。您应该只在 Activity 的 onCreate 或 fragment 的 onCreateView 中执行一次。

同样适用于 filterOne。如果该值是常量,因为它不会改变,您应该只在 onLocationChanged 调用之外检索它一次。


所以回答你的问题

is that repetitive use of Android Shared Preference storage make effect on performance?

是的,但只是因为你每次都重新初始化它。如果您听从我的建议,对性能几乎没有影响。

关于android - 重复使用 Android Shared Preference 存储会影响性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32824170/

相关文章:

android - Android 中具有两个子文本节点的节点的 Xpath 表达式

android - 将使用android软件包的纯java项目作为依赖关系添加到android studio中的android项目

android - 查找连接在 wifi 网络中的所有设备

Android -> 在主要 Activity 中加载共享首选项

android - 当 CheckBoxPreference 更改时获取值

安卓:SharedPreferences 问题

java - 下载管理器下载失败

android - 在我的 Android 应用程序之间共享 oauth token - 共享用户 ID、钥匙串(keychain)、AccountManager 或其他?

java - 在 SharedPreference 中保存通用类型的列表

android - 在 React Native 中访问共享首选项