长时间潜伏 - 第一次海报!我希望有人可以帮助解决我的小问题;
我有一个 PreferenceFragment ,它实现了一个 OnSharedPreferenceChangeListener ,然后它应该将一个sendBroadcast()发送到我的 AlarmReceiver 以便设置重复报警服务。 我可以看到侦听器注册onChange事件并一直向下到 getActivity()。sendBroadcast() - 但不幸的是,我的AlarmReceiver从未捕获广播。
这是我的PreferencesFragment;
for (i = 0; ...)
AlarmReceiver:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference preference = findPreference(key);
if (preference instanceof CheckBoxPreference) {
//Intent alarmReceiverIntent = new Intent(getActivity(), AlarmReceiver.class);
Intent alarmReceiverIntent = new Intent(getString(R.string.ACTION_SET_NOTIFICATIONS));
//alarmReceiverIntent.setAction(getActivity().getString(R.string.ACTION_SET_NOTIFICATIONS));
getActivity().getApplicationContext().sendBroadcast(alarmReceiverIntent);
}
最后是AndroidManifest.xml
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//This is just to see if the AlarmReceiver has caught the broadcast.
Log.v(TAG, "We are in the receiver - yay");
我希望有人可以提供帮助:)
答案 0 :(得分:0)
好的 - 所以我找到了解决方案! 如果您在接收广播时遇到问题,则必须将BroadCastReceiver注册为接收方。这解决了我的问题:)记得在onPause中取消注册并在onResume中注册。
E.g;
@Override
public void onResume() {
super.onResume();
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
getActivity().registerReceiver(alarmReceiver, new IntentFilter(getString(R.string.ACTION_SET_NOTIFICATIONS)));
}
@Override
public void onPause() {
super.onPause();
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
getActivity().unregisterReceiver(alarmReceiver);
}