Sunday, February 28, 2016

Loose Android communication between enteties (service, activity, fragment, etc) dynamic Broadcast

The receiver

public class XXXActivity extends Activity {
    

    BroadcastReceiver br = new BroadcastReceiver() {
        @Override        
        public void onReceive(Context context, Intent intent) {
            Log.i(P.Tag, "====Got Broadcast GOT_LOCATION_ACTION=====");
            // do something
        }
    };

    @Override    
    protected void onResume() {
        super.onResume();

        IntentFilter filter = new IntentFilter();
        filter.addAction(P.GOT_LOCATION_ACTION);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(br, filter);
    }

    @Override
    protected void onPause() {
      unregisterReceiver(br);
      super.onPause();
    }
}


The Sender

// this code can run on any entity with context (activity, service etc)
Intent i = new Intent(P.GOT_LOCATION_ACTION);
i.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(i);


* There is no need to define this receiver in the Manifest, since its dynamic.


No comments:

Post a Comment