使用自定义广播更改首选项时更新小部件

Update widget when preferences changed using custom broadcast

每次用户更改设置时,我都需要更新我的应用程序的小部件。

我有一个设置activity:

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class SettingsActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener {

public static final String customIntent = "CUSTOM_SETTINGS_CHANGED";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Display the fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new MainActivity.SettingsFragment())
            .commit();
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                      String key) {
    Intent intent = new Intent();
    intent.setAction(customIntent);
    this.sendBroadcast(intent);
    }
}

我已将该自定义意图添加到清单中:

<action android:name="CUSTOM_SETTINGS_CHANGED" />

但是设置更改后小部件不会立即更新。所以我的自定义广播要么没有发送,要么没有收到。我的代码有什么问题?

// this part important in manifest declaration
package com.xmpls.onetwothree.abc;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class SettingsActivity {


    public class SettingsActivity extends Activity implements 
            SharedPreferences.OnSharedPreferenceChangeListener {
        // Change like this
        public static final String CUSTOM_SETTINGS_CHANGED = "com.xmpls.onetwothree.abc.custompls";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Display the fragment as the main content.
            getFragmentManager().beginTransaction();
            /* More code here. . .*/
        }
        /* And some here. . .*/
    }
================================================================================
and in manifest U must registred ACTION like this:
<action android:name="com.xmpls.onetwothree.abc.CUSTOM_SETTINGS_CHANGED" />

我使用了不同的方法。

在我的 main activity 我添加了这个:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    <...>
    SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            Intent intent = new Intent();
            intent.setAction(customIntent);
            sendBroadcast(intent);
        }
    };
    <...>
}

似乎由于某种原因从未调用过 onSharedPreferenceChanged。我不知道为什么,但至少我找到了一种方法来完成这项工作。