0

我正在尝试使用用户首选项复选框在状态栏上显示或不显示通知。到目前为止,我已经这样做了:

MainActivity.java

@Override
public void UserPref {

    String notificationTitle = "ASD";
    String notificationMessage = "ASD ASD ASD";

    Intent targetIntent = new Intent(this, MainActivity.class);

    int requestCode = AppSingleton.NOTIFICATION_ID;

    PendingIntent contentIntent = PendingIntent.getActivity(this,
            requestCode, targetIntent, 0);
    String statusBarTickerText = "ASD ASD ASD";
    int icon = R.drawable.ic_launcher;

    Notification notification = new Notification(icon, statusBarTickerText,
            System.currentTimeMillis());
    notification.flags = Notification.FLAG_ONGOING_EVENT
            | Notification.FLAG_NO_CLEAR;
    notification.setLatestEventInfo(this, notificationTitle,
            notificationMessage, contentIntent);

    nm.notify(AppSingleton.NOTIFICATION_ID, notification);
}

我可以一直显示通知。但现在我想添加用户首选项,用户可以通过它禁用或启用通知。这是我的 PreferenceActivity 代码:

用户偏好.java

public class UserPreference extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.prefs);

    final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager()
            .findPreference("Checkbox");

    checkboxPref
            .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference preference,
                        Object newValue) {
                     Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());       
                        return true;
                }
            });
   }
}

从 MainActivity.java 检查 CheckBox 时,我无法调用该函数,但我可以在 DDMS 中打印布尔值。

请查看并纠正我做错了什么,并帮助我克服这个问题。

4

1 回答 1

1

您不需要为偏好的更改注册侦听器。您可以在使用以下代码发送通知之前检查标志,只需获取保存在默认共享首选项中的复选框的值:

SharedPreferences defaultSettings = PreferenceManager.getDefaultSharedPreferences(this);
boolean notifyEnabled = defaultSettings.getBoolean("Checkbox", true);

if(notifyEnabled) {
    // Perform code to send notification 
}

如果您仍然希望在复选框值更改时以某种方式收到通知,您可以通过覆盖 onSharedPreference() 方法来实现:

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, 
    String key)
{
    if(key.compareToIgnoreCase("Checkbox") == 0)
    {
        boolean isChecked = sharedPreferences.getBoolean("Checkbox", false);
        if(isChecked)
        {
            // Checkbox is checked
        }
        else
        {
            // Checkbox has been unchecked
        }
    }
}
于 2012-09-06T07:25:28.373 回答