2016-04-28 52 views
0

長時間潛伏 - 第一次海報!我希望有人能幫助解決我的小問題;PreferenceFragment中的sendBroadcast問題(字符串操作)

我有一個PreferenceFragment它實現了OnSharedPreferenceChangeListener然後應以建立一個重複報警服務觸發一個sendBroadcast()我AlarmReceiver。 我可以看到,監聽器註冊了onChange事件並一路下降到getActivity()。sendBroadcast() - 但不幸的是廣播從來沒有被我的AlarmReceiver捕獲。

這是我的PreferencesFragment;

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); 
    } 

AlarmReceiver:

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"); 

最後在AndroidManifest.xml中

<receiver 
    android:name=".AlarmReceiver" 
    android:enabled="true"> 
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    </intent-filter> 
    <intent-filter> 
     <action android:name="dk.aau.student.b211.sleepattention.SET_NOTIFICATIONS" /> 
    </intent-filter> 
</receiver> 

我希望有一個人在那裏,可以幫助:)

+0

檢查你的'ACTION_SET_NOTIFICATIONS' –

回答

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); 
}