Created
          July 4, 2012 07:29 
        
      - 
      
- 
        Save roosmaa/3045908 to your computer and use it in GitHub Desktop. 
    Dynamically registered BroadcastReceivers pattern
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package net.roosmaa.example; | |
| import android.content.BroadcastReceiver; | |
| import android.content.Context; | |
| import android.content.Intent; | |
| import android.content.IntentFilter; | |
| public class Sample | |
| { | |
| private Context mContext; | |
| private BroadcastReceiver mMyReceiver; | |
| // .. | |
| /** Registeres the {@link MyReceiver} if it hasn't been registered yet. */ | |
| private void registerReceiver() | |
| { | |
| if (mMyReceiver != null) | |
| return; | |
| mMyReceiver = new MyReceiver(); | |
| mContext.registerReceiver(mMyReceiver, new IntentFilter("myAction")); | |
| } | |
| /** Unregisteres the {@link MyReceiver} if it was registered previously. */ | |
| private void unregisterReceiver() | |
| { | |
| if (mMyReceiver == null) | |
| return; | |
| mContext.unregisterReceiver(mMyReceiver); | |
| mMyReceiver = null; | |
| } | |
| // .. | |
| private class MyReceiver extends BroadcastReceiver | |
| { | |
| @Override | |
| public void onReceive(Context context, Intent intent) | |
| { | |
| // Do whatever here | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment