调用onSharedPreferenceChanged后重新启动应用程序

时间:2015-07-27 13:12:14

标签: android

如何在调用onSharedPreferenceChanged后重新启动应用程序?

ActivityPreferences.java:

[..]
public static class FragmentPreferences extends PreferenceFragment {
        private Context context;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            context = getActivity();
            PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, false);
            addPreferencesFromResource(R.xml.preferences);

            final SharedPreferences sp = context.getSharedPreferences("PREFERENCE_KEY", Context.MODE_PRIVATE);
            SharedPreferences.OnSharedPreferenceChangeListener spChanged = new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                    context.finish();
                    startActivity(new Intent(ActivityPreferences.this, ActivityLogin.class));
                }
            };
        }
    }

这是我尝试过的,但我无法拨打finish()

如果listpreference s1_theme设置为亮/暗,我想更改主题:

ActivityMain.java:

@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Context context = getApplicationContext();
        final SharedPreferences sp = context.getSharedPreferences("PREFERENCE_KEY", Context.MODE_PRIVATE);
        if (sp.getString("s1_theme", "-1") == "light"){
                setTheme(R.style.AppTheme_BaseLight);
        } else {
            setTheme(R.style.AppTheme_BaseDark);
        }
        setContentView(R.layout.activity_main);
        [..]

4 个答案:

答案 0 :(得分:2)

尝试此代码...这将重新启动MainActivity ...

                    this.finish();
                    Intent refresh = new Intent(this, MainActivity.class);
                    startActivity(refresh);

使用此代码在MainActivity中创建一个方法,并通过传递上下文从要重新启动的fragment类中调用它...

答案 1 :(得分:1)

对于主题更改,我认为您应该有一个全局变量,您可以检查每个活动(在其onResume函数中)与它使用的最后一个活动,然后如果它们不同则重新启动。

以下是重新启动活动的代码:

  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public static void restartActivity(final Activity activity)
    {
    if(android.os.Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
      activity.recreate();
    else
      {
      new Handler().post(new Runnable()
      {
      @Override
      public void run()
        {
        activity.overridePendingTransition(0,0);
        activity.startActivity(activity.getIntent());
        }
      });
      activity.finish();
      }
    }

答案 2 :(得分:1)

我使用的主题完全错误:)要动态更改主题/样式,您可以按照以下步骤操作:

<强> 1。定义主题:

<!-- values/attr.xml -->
<resources>
    <attr name="testcolor" format="color" />
    ..
</resources>

<!-- values/styles.xml -->
<resources>
    <style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
        <item name="backgroundLinearLayout">@color/backgroundLinearLayout</item>
        ..
    </style>

    <style name="AppTheme.Light" parent="Theme.AppCompat.NoActionBar">
        <item name="backgroundLinearLayout">@color/backgroundLinearLayout</item>
        ..
    </style>
</resources>

<!-- layout/layout_1.xml -->
<LinearLayout
   ..
   android:background="?attr/backgroundLinearLayout">
</LinearLayout>

<强> 2。创建/编辑“设置活动”

<!-- xml/preference_main.xml -->

<PreferenceScreen>
    <PreferenceCategory android:title="Themes">
        <SwitchPreference
            android:defaultValue="false"
            android:key="theme_preference_key"
            android:title="Enable for darkmode"/>
    </PreferenceCategory>
    ..
</PreferenceScreen>

// SettingsActivity Class

public class SettingsActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener {
    public static final int RESULT_CODE_THEME_UPDATED = 1;
    private SharedPreferences sp;
    private TypedArray ta;
    private int backgroundLinearLayout;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        context = getApplicationContext();
        sp = PreferenceManager.getDefaultSharedPreferences(this);
        changeTheme(sp.getBoolean("theme_preference_key", false));
        super.onCreate(savedInstanceState);
        findPreference("theme_preference_key").setOnPreferenceChangeListener(new RefershActivityOnPreferenceChangeListener(RESULT_CODE_THEME_UPDATED));
        ..
    }

    private void changeTheme(Object newValue) {
        int[] attrs = {android.R.attr.backgroundLinearLayout};
        if (sp.getBoolean("theme_preference_key", false)) {
            setTheme(R.style.AppTheme_Dark);
            ta = obtainStyledAttributes(R.style.AppTheme_Dark, attrs);
            backgroundLinearLayout= ta.getColor(0, Color.BLACK);
        } else {
            setTheme(R.style.AppTheme_Light);
            ta = obtainStyledAttributes(R.style.AppTheme_Light, attrs);
            backgroundLinearLayout= ta.getColor(0, Color.BLACK);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ta.recycle();
    }

    private class RefershActivityOnPreferenceChangeListener implements OnPreferenceChangeListener {
        private final int resultCode;

        public RefershActivityOnPreferenceChangeListener(int resultCode) {
            this.resultCode = resultCode;
        }

        @Override
        public boolean onPreferenceChange(Preference p, Object newValue) {
            setResult(resultCode);
            finish();
            startActivity(getIntent());
        return true;
    }
}

//MainActivity Class

public class ActivityMain extends AppCompatActivity {
    private int SETTINGS_ACTION = 1;
    private SharedPreferences sp;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        context = getApplicationContext();
        sp = PreferenceManager.getDefaultSharedPreferences(this);
        setTheme((sp.getBoolean("s1_theme", false)) ? R.style.AppTheme_Dark : R.style.AppTheme_Light);
        super.onCreate(savedInstanceState);
        ..
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SETTINGS_ACTION) {
            if (resultCode == SettingsActivity.RESULT_CODE_THEME_UPDATED) {
                finish();
                startActivity(getIntent());
                return;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

答案 3 :(得分:0)

您可以使用特定操作启动意图,例如ACTION_REFRESH

Intent intent = new Intent(context, MainActivity.class);
intent.setAction(MainActivity.ACTION_REFRESH);
context.startActivity(intent);

然后在MainActivity#onCreate()MainActivity#onNewIntent()上处理此意图及其操作,并使用Intent.FLAG_ACTIVITY_CLEAR_TOP标记启动新标记

protected void onNewIntent(Intent intent) {
  if (MainActivity.ACTION_REFRESH.equals(intent.getAction()) {
    finish();
    Intent intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(intent);
  }
}

protected void onCreate(Bundle savedInstanceState) {
  // Same thing
}

您可能需要以某种方式调整此代码,但希望您明白这一点。