从动态壁纸中的设置页面检索数据

Retrieving data from settings page in live wallpaper

考虑以下代码作为Android中动态壁纸的设置页面:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="@string/livewallpaper_settings"
    android:key="livewallpaper_settings">

    <ListPreference
        android:key="livewallpaper_testpattern"
        android:title="@string/livewallpaper_settings_title"
        android:summary="@string/livewallpaper_settings_summary"
        android:entries="@array/livewallpaper_testpattern_names"
        android:entryValues="@array/livewallpaper_testpattern_prefix"/>
    <CheckBoxPreference android:key="livewallpaper_movement"
        android:summary="@string/livewallpaper_movement_summary"
        android:title="@string/livewallpaper_movement_title"
        android:summaryOn="Moving test pattern"
        android:summaryOff="Still test pattern"/>
</PreferenceScreen>

它显示了一个设置页面,关于显示设置的一切都很好。如何保存此设置并在创建动态壁纸时使用它们?

还有,在onCreate方法中读取设置是否正确?

我找到了答案:

package ca.jvsh.livewallpaper;

import ca.jvsh.livewallpaper.R;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;

public class LiveWallpaperSettings extends PreferenceActivity
    implements SharedPreferences.OnSharedPreferenceChangeListener
{
    @Override
    protected void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        getPreferenceManager().setSharedPreferencesName(LiveWallpaper.SHARED_PREFS_NAME);
        addPreferencesFromResource(R.xml.livewallpaper_settings);
        getPreferenceManager().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    @Override
    protected void onDestroy()
    {
        getPreferenceManager().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
        super.onDestroy();
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key)
    {
    }
}

这是设置页面的 java class。 这是用于读取设置的:

    TestPatternEngine()
    {
        ...

        mPreferences = LiveWallpaper.this.getSharedPreferences(SHARED_PREFS_NAME, 0);
        mPreferences.registerOnSharedPreferenceChangeListener(this);
        onSharedPreferenceChanged(mPreferences, null);
    }

    public void onSharedPreferenceChanged(SharedPreferences prefs,
            String key)
    {
        mShape = prefs.getString("livewallpaper_testpattern", "smpte");
        mMotion = prefs.getBoolean("livewallpaper_movement", true);
        readColors();
    }