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

时间:2015-03-13 14:25:31

标签: android widget android-broadcast

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

我有一项设置活动:

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" />

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

2 个答案:

答案 0 :(得分:0)

// 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" />

答案 1 :(得分:0)

我使用了不同的方法。

在我的主要活动中,我添加了这个:

@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由于某种原因从未被调用过。我不知道为什么,但至少我找到了一种方法来使这项工作。